java examples
Home Java Examples Resources Java Interview Questions
Brainpower SEO

How to 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 com.javacoderanch.example.commons.lang;

import java.util.Calendar;
import java.util.Date;
import org.apache.commons.lang.time.DateFormatUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.lang.time.FastDateFormat;

public class DateRounding {
    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 = 2008-04-05T00:34:55+07:00
nearestSecond = 2008-04-05T00:34:56+07:00
nearestMinute = 2008-04-05T00:35:00+07:00
nearestHour = 2008-04-05T01:00:00+07:00