1.14. Rounding Date Objects
Problem
You need to round a date to the nearest second, minute, hour, day, month, or year.
Solution
Use DateUtils to round Date
objects to the nearest Calendar field.
DateUtils.round()
can round to almost every
Calendar field, including
Calendar.SECOND,
Calendar.MINUTE, Calendar.HOUR,
Calendar.DAY_OF_MONTH,
Calendar.MONTH, and
Calendar.YEAR. The following example demonstrates
the use of DateUtils.round( ):
import org.apache.commons.lang.time.FastDateFormat; import org.apache.commons.lang.time.DateFormatUtils; import org.apache.commons.lang.time.DateUtils; FastDateFormat dtFormat = DateFormatUtils.ISO_DATETIME_FORMAT; Date now = new Date( ); Date nearestHour = DateUtils.round( now, Calendar.HOUR ); Date nearestDay = DateUtils.round( now, Calendar.DAY_OF_MONTH ); Date nearestYear = DateUtils.round( now, Calendar.YEAR ); System.out.println( "Now: " + dtFormat.format( now ) ); System.out.println( "Nearest Hour: " + dtFormat.format( nearestHour ) ); System.out.println( "Nearest Day: " + dtFormat.format( nearestDay ) ); System.out.println( "Nearest Year: " + dtFormat.format( nearestYear ) );
This example creates an object representing the current time and
rounds this date to the nearest hour, day, and year. Assuming that
the current date is March 28, 2004, and the current time is 1:48
P.M., this program creates the following output using the
FastDateFormat class from the previous recipe:
Now: 2004-03-28T13:48:12 Nearest Hour: 2004-03-28T14:00:00 Nearest ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access