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

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

    A commented implementation for Java 8. Accepts arbitrary rounding units and increments:

     public static ZonedDateTime round(ZonedDateTime input, TemporalField roundTo, int roundIncrement) {
        /* Extract the field being rounded. */
        int field = input.get(roundTo);
    
        /* Distance from previous floor. */
        int r = field % roundIncrement;
    
        /* Find floor and ceiling. Truncate values to base unit of field. */
        ZonedDateTime ceiling = 
            input.plus(roundIncrement - r, roundTo.getBaseUnit())
            .truncatedTo(roundTo.getBaseUnit());
    
        ZonedDateTime floor = 
            input.plus(-r, roundTo.getBaseUnit())
            .truncatedTo(roundTo.getBaseUnit());
    
        /*
         * Do a half-up rounding.
         * 
         * If (input - floor) < (ceiling - input) 
         * (i.e. floor is closer to input than ceiling)
         *  then return floor, otherwise return ceiling.
         */
        return Duration.between(floor, input).compareTo(Duration.between(input, ceiling)) < 0 ? floor : ceiling;
      }
    

    Source: myself

提交回复
热议问题