How do I get the nearest hour, minute, second of a date?

This example demonstrate how to use the DateUtils.round() method to get the nearest hour, minute and second of a date.

package org.kodejava.example.commons.lang;

import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang.time.FastDateFormat;

import java.util.Calendar;
import java.util.Date;

public class DateRoundingDemo {
    public static void main(String[] args) {
        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));

Here are the program results:

now = 2017-05-12T22:51:59+08:00
nearestSecond = 2017-05-12T22:52:00+08:00
nearestMinute = 2017-05-12T22:52:00+08:00
nearestHour = 2017-05-12T23:00:00+08:00

Maven Dependencies

<!-- -->

Wayan Saryada

Founder at Kode Java Org
I am a programmer, a runner, a recreational diver, currently live in the island of Bali, Indonesia. Mostly programming in Java, Spring Framework, Hibernate / JPA. You can support my works by donating here. Thank you 🥳

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.