【问题标题】:how to check whether a given string is between particular time range如何检查给定字符串是否在特定时间范围之间
【发布时间】:2019-10-16 00:34:59
【问题描述】:

给定像“09:00”这样的开始字符串和像“10:00”这样的结束字符串,我如何检查当前时间是否在这个范围内。我搜索了很多,但大多数都需要更高的 API 级别,我的最低 android 目标版本是 20。请建议一些 Kotlin 中的代码。

fun Date.toString(format: String, locale: Locale = Locale.getDefault()): String {
        val formatter = SimpleDateFormat(format, locale)
        return formatter.format(this)
    }

    fun getCurrentDateTime(): Date {
        return Calendar.getInstance().time
    }

    val date = getCurrentDateTime()
    val currentDate = date.toString("dd/MM/yyyy")
    val currentTime: String = date.toString("HH:mm")

这就是我设法获取日期和时间的方式

【问题讨论】:

  • 如果时间字符串严格遵循这种格式(24小时制),那么简单地比较字符串就足够了。
  • 在 Android API 级别 20 上,将 ThreeTenABP 添加到您的项目中,并使用您找到的使用 java.time(现代 Java 日期和时间 API)的答案。通过这种方式,您可以避免使用陈旧且设计不佳的Calendar,尤其是SimpleDateFormat。
  • 同时将开始和结束时间保留为字符串是一个糟糕的主意。改为保留 LocalTime 对象。他们的isBefore 和/或isAfter 方法会很方便。

标签: android date kotlin time


【解决方案1】:

我希望这对你有用。

像这样创建方法/函数,

private fun checkCurrentTimeIsBetweenGivenString(s1:String,s2:String): Boolean{

        val simpleDateFormat= SimpleDateFormat("dd/MM/yyyy HH:mm")

        val date1:Date=simpleDateFormat.parse(s1)

        val date2:Date=simpleDateFormat.parse(s2)

        val d= Date()

        val s3=simpleDateFormat.format(d)

        val date3=simpleDateFormat.parse(s3)

        return  date3 >= date1  &&  date3 <= date2
    }

这样使用,

if(checkCurrentTimeIsBetweenGivenString("16/10/2019 10:00","16/10/2019 12:00")){
            Log.e("output","Current time is between this range")
        }else{
            Log.e("output","Current time is not between this range")
        }

如果当前时间在给定字符串之间,则该部分将起作用,否则部分将起作用。

【讨论】:

  • 嗨,感谢它真正有效的解决方案,但我遇到了一些我在编辑中解释过的问题。请调查一下
【解决方案2】:

我觉得这会奏效

 private fun checkDate(startDate: String, endDate: String): Boolean {
    val simpleDateFormat = SimpleDateFormat("dd/MM/yyyy")
    val dateStart: Date = simpleDateFormat.parse(startDate)
    val dateEnd: Date = simpleDateFormat.parse(endDate)
    val currentDate = Date()
    return currentDate.after(dateStart) && currentDate.before(dateEnd)
 }

示例:

if (checkDate("16/10/2019 05:13", "16/12/2019 09:12")) {
     //Date is between range
} else {
     //Date is not between range
}

如果当前时间在范围内返回true,否则返回false,请检查

【讨论】:

    猜你喜欢
    • 2016-10-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-07
    • 2020-02-04
    • 2020-07-28
    相关资源
    最近更新 更多