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

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

    One more alternate approach using java Instant api.

    Instant instant =  Instant.now();
    int intervalInMinutes = 10;
    instant.truncatedTo(ChronoUnit.MINUTES).minus(instant.atZone(ZoneId.of("UTC")).getMinute() % (1* intervalInMinutes),ChronoUnit.MINUTES);
    

提交回复
热议问题