tags:

views:

98

answers:

4

I need to calculate a java.util.Date for a beginning of a today day (00:00:00 a.m. of a today day). Does someone know something better than resetting fields of java.util.Calendar:

Calendar cal = Calendar.getInstance();
cal.set(Calendar.AM_PM, Calendar.AM);
cal.set(Calendar.HOUR, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
+1  A: 

I'm in the same boat, and what you have provided is how I do it. I do have it in a DateUtil.stripToMidnight(...) function...

But just remember to consider TimeZones when doing all this, as 0:00am here, will not be the same in another part of the world.

There might be a way to do this in JodaTime, but I don't know of it.

stevemac
+6  A: 

If you don't bother about time zones then your solution is ok. Otherwise it's worth to look at JodaTime.

If you eventually decide to switch to JodaTime, then you can use DateMidnight class which is supposed to be used in your situation.

Roman
A: 

Another option without additional libraries:

import java.sql.Date;

public class DateTest {
    public static void main(String[] args) {
        long MS_PER_DAY = 24L * 60 * 60 * 1000;
        long msWithoutTime = (System.currentTimeMillis() / MS_PER_DAY) * MS_PER_DAY;
        Date date = new Date( msWithoutTime );
        System.out.println( date.toGMTString());
    }
}
stacker
+2  A: 

The following code will return the current date's calendar object with time as 00:00:00

        Calendar current = Calendar.getInstance();
        current.set(current.get(Calendar.YEAR),current.get(Calendar.MONTH),current.get(Calendar.DATE),0,0,0);

It will not consider the timezone values. It is same as your code. Only change is that it done all resets in single line.

Joe