How to round time to the nearest quarter hour in java?

后端 未结 14 2697
小鲜肉
小鲜肉 2020-11-27 14:59

Given today\'s time e.g. 2:24PM, how do I get it to round to 2:30PM?

Similarly if the time was 2:17PM, how do I get it to round to 2:15PM?

14条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-27 15:26

    With the answer above you end up with all kind of interesting code to handle overflows to hours, days etc.

    I would use the time in ms since the epoch.

    add 7.5minutes or 7.5x60x1000 = 450000

    and truncate to a multiple of 900000

    new Date(900000 * ((date.getTime() + 450000) / 900000))
    

    This works, because the time where the ms time starts happens to be 00:00:00. And since all time zones in the world change in 15min steps, this does not affect rounding to quarters.

    (Oops, I had a 0 too much and forgot some important parentheses : it is still too early)

提交回复
热议问题