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

后端 未结 14 2702
小鲜肉
小鲜肉 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:22

    If you just want to round down this is a more readable version using Java Time API:

    LocalDateTime time = LocalDateTime.now();
    LocalDateTime lastQuarter = time.truncatedTo(ChronoUnit.HOURS)
                                    .plusMinutes(15 * (time.getMinute() / 15));
    

    output:

    2016-11-04T10:58:10.228

    2016-11-04T10:45:00

提交回复
热议问题