views:

570

answers:

5

Hi Folks,

I have a Java Date object containing date and time information, e.g. 2008-01-01 13:15:00. I want to write a method that cuts off the time information so I only have the date left, e.g. 2008-01-01 00:00:00.

Do you have a tip? I tried doing something like this

(timestamp / (24 * 60 * 60 * 1000)) * (24 * 60 * 60 * 1000)

but I ran into problems with the timezone...

Thanks for your help!

Marco

+4  A: 

The recommended way to do date/time manipulation is to use a Calendar object:

Calendar cal = Calendar.getInstance(); // locale-specific
cal.setTime(dateObject);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
long time = cal.getTimeInMillis();
cletus
`getTimeInMillis`
Wesho
A: 

Use the Calendar class's set() method to set the HOUR_OF_DAY, MINUTE, SECOND and MILLISECOND fields to zero.

Michael Borgwardt
+4  A: 
Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
date = cal.getTime();
jitter
+1 just for fixing minor errors in my answer. :)
cletus
+2  A: 

Have you looked at Joda ? It's a much easier and more intuitive way to work with dates and times. For instance you can convert trivially between (say) LocalDateTime and LocalDate objects.

e.g. (to illustrate the API)

LocalDate date = new LocalDateTime(milliseconds).toLocalDate()

Additionally it solves some thread-safety issues with date/time formatters and is to be strongly recommended for working with any date/time issues in Java.

Brian Agnew
-1 Does this relate to the question at all?
jitter
Downvoted why ?
Brian Agnew
I believe it does. It's a recommendation to use a better library rather than battle with the broken java.util classes (as evidenced by the question)
Brian Agnew
Joel
AND it's thread safe, as Brian mentioned.
Joel
I confess I was faintly surprised not to find anyone else mentioning it. Thanks for emphasising that.
Brian Agnew
Wow... Joda looks interesting. I think I will use this in other projects! Thanks for the hint!
Marco
It's very good indeed. I use it in everything now....
Brian Agnew
+1  A: 

Have you looked at the DateUtils truncate method in Apache Commons Lang?

Date truncatedDate = DateUtils.truncate(new Date(), Calendar.DATE);

will remove the time element.

A_M