How to round DateTime of Joda library to the nearest X minutes?

后端 未结 6 1564
[愿得一人]
[愿得一人] 2020-12-28 14:42

How to round DateTime of Joda library to the nearest X minutes ?
For example:

X = 10 minutes
Jun 27, 11:32 -> Jun 27, 11         


        
6条回答
  •  半阙折子戏
    2020-12-28 15:00

    I have a function for LocalTime class but I think it's very easy to adopt my sample for your case:

    (Kotlin lang)

    fun LocalTime.round(roundValue: Int): LocalTime {
        val timeInMillis = this.millisOfDay
        val remainder = timeInMillis % roundValue
        return when {
            remainder < (roundValue / 2) -> LocalTime.fromMillisOfDay((timeInMillis - remainder).toLong())
            else -> LocalTime.fromMillisOfDay((timeInMillis + (roundValue - remainder)).toLong())
        }
    }
    

    And usage:

    var userWakeTime = LocalTime(6, 42)
    userWakeTime = userWakeTime.round(15 * 60 * 1000) // userWakeTime = 6:45
    

提交回复
热议问题