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

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

    Maybe you can use an utility library for manipulating Dates, here for example you have a round method which can be useful for you:

    http://commons.apache.org/lang/api-2.4/org/apache/commons/lang/time/DateUtils.html#round%28java.util.Calendar,%20int%29

    Here an example in code:

        FastDateFormat formatter = DateFormatUtils.ISO_DATETIME_TIME_ZONE_FORMAT;
    
        Date now = new Date();
        System.out.println("now = " + formatter.format(now));       
    
        // Get nearest second
        Date nearestSecond = DateUtils.round(now, Calendar.SECOND);
        System.out.println("nearestSecond = " + formatter.format(nearestSecond));
    
        // Get nearest minute
        Date nearestMinute = DateUtils.round(now, Calendar.MINUTE);
        System.out.println("nearestMinute = " + formatter.format(nearestMinute));
    
        // Get nearest hour
        Date nearestHour   = DateUtils.round(now, Calendar.HOUR);
        System.out.println("nearestHour = " + formatter.format(nearestHour));
    

提交回复
热议问题