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 Dat…

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;

Author: Laird Nelson

Devoted husband and father; working on Helidon at the intersection of Java, Jakarta EE, architecture, Kubernetes and microservices at Oracle; open source guy; Hammond B3 player and Bainbridge Islander.