Java Date cut off time information

Marco picture Marco · Dec 15, 2009 · Viewed 204.3k times · Source

I have a Java Date object containing date and time information. I want to write a method that cuts off the time information, truncates the hours-minutes-seconds, so I only have the date left.

Example input:

2008-01-01 13:15:00

Expected output:

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.

Answer

cletus picture cletus · Dec 15, 2009

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();