Reputation: 117106
It's not clear in the java doc what the difference between DateUtils.ceiling and DateUtils.truncate is. Is the java doc wrong? Can someone clarify this?
ceiling
public static Date ceiling(Date date, int field)
Ceil this date, leaving the field specified as the most significant field.
For example, if you had the datetime of 28 Mar 2002 13:45:01.231, if you passed with HOUR, it would return 28 Mar 2002 13:00:00.000. If this was passed with MONTH, it would return 1 Mar 2002 0:00:00.000.
vs
truncate
public static Date truncate(Date date, int field)
Truncate this date, leaving the field specified as the most significant field.
For example, if you had the datetime of 28 Mar 2002 13:45:01.231, if you passed with HOUR, it would return 28 Mar 2002 13:00:00.000. If this was passed with MONTH, it would return 1 Mar 2002 0:00:00.000.
Upvotes: 10
Views: 13751
Reputation: 7349
To add on to Jim's answer, I suspect there is a Javadoc error on the ceiling method. The description for ceiling(Date,int) was updated with the 3.0 javadoc (compare to the 2.5 javadoc for the same method)... and although the others weren't updated, that method uses code common to the Calendar version... Or using a simple test case you could see that they both behave the same (for me with 3.1 at least :) )
@Test
public void testCeil() {
final Calendar date = new GregorianCalendar();
date.clear();
date.set(2002, 3, 28, 13, 45, 01);
System.out.println(date.getTime());
System.out.println(DateUtils.ceiling(date, Calendar.HOUR).getTime());
System.out.println(DateUtils.ceiling(date.getTime(), Calendar.HOUR));
System.out.println(DateUtils.truncate(date, Calendar.HOUR).getTime());
System.out.println(DateUtils.truncate(date.getTime(), Calendar.HOUR));
System.out.println(date.getTime());
}
Upvotes: 8
Reputation: 11805
The documentation on some of the older versions for the ceil() method is WRONG. It has been corrected at some point, and here's the docs from 3.1:
public static Date ceiling(Date date,
int field)
Ceil this date, leaving the field specified as the most significant field.
For example, if you had the datetime of 28 Mar 2002 13:45:01.231, if you passed with HOUR, it would return 28 Mar 2002 14:00:00.000. If this was passed with MONTH, it would return 1 Apr 2002 0:00:00.000.
So, while ceil() and trunc() both minimize all the remaining fields (in some cases sets to 0, but for MONTH it will set the day to 1), ceil() will actually increment the field you pass in by 1, whereas trunc will not.
Upvotes: 3
Reputation: 3634
The answer is in the documentation:
The truncate, ceiling and round methods could be considered the Math.floor(), Math.ceil() or Math.round versions for dates This way date-fields will be ignored in bottom-up order.
Which I would interpret as "You're correct, but there is a reason"
Upvotes: 6