Search code examples
androiddatetimekotlinjodatime

Android Joda-Time with Kotlin


I am trying to create a function to check a given string time HH:mm is in range of another comparing to now.

Example: if the current hour is between 12:35 and 15:00 return true

But I always got false even if the current time is in range..

fun isTimeInRange(before: String, after: String): Boolean {
    val now = DateTime.now()
    val format = DateTimeFormat.forPattern("HH:mm")
    return now >= DateTime.parse(before, format) && now <= DateTime.parse(after, format)
}

Solution

  • You have to set before/after date to today's date. try this:

    fun isTimeInRange(start: String, end: String): Boolean {
        val now = DateTime.now()
        val format = DateTimeFormat.forPattern("HH:mm")
        val startTime: LocalTime = format.parseLocalTime(start)
        val endTime: LocalTime = format.parseLocalTime(end)
        val timeZone = DateTimeZone.getDefault()
        val today: LocalDate = LocalDate.now(timeZone)
        val startMoment: DateTime = today.toLocalDateTime(startTime).toDateTime(timeZone)
        val endMoment: DateTime = today.toLocalDateTime(endTime).toDateTime(timeZone)
        return now.isAfter(startMoment) && now.isBefore(endMoment)
    }