Friday, October 19, 2007

Truncate date object

Unfortunately Date object doesn't provide a way to truncate a date effectively removing its time (resetting to 0) easily.

My first try is to use Calendar and set the hour, minute, second and millisecond fields to 0.
Calendar calendar = Calendar.getInstance();
calendar.setTime(theDate);
calendar.set(Calendar.HOUR, 0);
.... same with min, sec, mil.

Then came up DateUtils from apache common lang, interesting utility, but the javadoc doesn't explain much on how truncating the time and strangely it choose instead to pick parameter which is specified as the most significant field to preserve(when all I want to do is to remove the time).
Anyway after trial-error, here is the code I came up with :
DateUtils.truncate(theDate, Calendar.DATE);

I was expecting only date is preserved, month and anything else will be gone, but it works! Thanks to DateUtils.

5 comments:

Unknown said...

I'm new to java, but very experienced in oracle and dot.net. I thought that for all these years java is mature and well designed language and classes, but now I think java people should come with much much better and more straightforward solution for dates, as they exists both in oracle and in .net already. So simple and so effective. But in java - no!

For example, to compare two datetime-s in oracle for equality only by date portion, expression is "trunc(date1)=trunc(date2)". In java, i should write 10 lines of code or using some trird-party solutions for such an essential thing! It's a real shame for java.

Anonymous said...

Hi Vedran,

Your comment is very useful here, thanks for the contribution!

Sridhar Sarnobat said...

Just what I was looking for. Thanks.

Anonymous said...

You may want use Calendar.HOUR_OF_DAY

Anonymous said...

DateUtils.trucate() does not work properly with daylight saving time.
e.g.:
DateUtils.truncate(date, Calendar.DATE);

Instead of showing 10/10/2010, it shows 09/10/2010 23:00:00.