Zeroing out times in java.util.Date the right way

File this one under The Mob Is Coming For java.util.Date Author Alan Liu With Flaming Torches And Pitchforks (one in a long series).

Folks who have worked with Java’s java.util.Date and java.util.Calendar classes know that when you create a new Date object without any arguments it is initialized with a long representing the number of milliseconds since the epoch.

Sometimes you need a Date that just has its date fields initialized. Here is the only way to do it properly, ensuring that all date fields are set to their defaults, and all time fields are set to their minimums. Anything else runs the risk of missing a time or date field or two, or uses a deprecated constructor, or is not performant, or all three.

final Calendar calendarNow = Calendar.getInstance();
assert calendarNow != null;
calendarNow.set(Calendar.HOUR_OF_DAY, calendar.getMinimum(Calendar.HOUR_OF_DAY));
calendarNow.set(Calendar.HOUR, calendar.getMinimum(Calendar.HOUR)); // for maximum correctness and safety you need to set both (!)
calendarNow.set(Calendar.MINUTE, calendar.getMinimum(Calendar.MINUTE));
calendarNow.set(Calendar.SECOND, calendar.getMinimum(Calendar.SECOND));
calendarNow.set(Calendar.MILLISECOND, calendar.getMinimum(Calendar.MILLISECOND));
calendarNow.set(Calendar.AM_PM, calendar.getMinimum(Calendar.AM_PM)); // this makes it "really correct" for future modifications
final Date now = calendarNow.getTime();
assert now != null;
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s