Marco Marco - 5 months ago 33
Java Question

Java Date cut off time information

I have a Java Date object containing date and time information. I want to write a method that cuts off the time information 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

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