Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Recommended use for Joda-Time's DateMidnight

The javdoc for LocalDate#toDateMidnight reads as follows:

As from v1.5, you are recommended to avoid DateMidnight and use toDateTimeAtStartOfDay() instead because of the exception detailed below.

This method will throw an exception if the default time zone switches to Daylight Savings Time at midnight and this LocalDate represents that switchover date. The problem is that there is no such time as midnight on the required date, and as such an exception is thrown.

The fact that midnight does not exist in certain time zones seems like reason enough to avoid using DateMidnight entirely (assuming your code is not using a fixed time zone that is known not to have this DST situation and will never need to use different time zones in the future).

However, DateMidnight is not deprecated and there is no similar recommendation or warning in the javadoc for the DateMidnight class itself. Furthermore, the DateMidnight constructor happily accepts an instant and time zone such that midnight does not exist on the given day, rather than throwing an IllegalArgumentException like LocalDate#toDateMidnight. The resulting DateMidnight behaves like a DateTime with time at start of day.

When midnight does not exist on a given day, why does LocalDate#toDateMidnight throw an exception while the DateMidnight constructor does not? What is the recommended use case for DateMidnight if any?

like image 662
oby1 Avatar asked Jul 16 '13 00:07

oby1


People also ask

What is the replacement of Joda time?

time (JSR-310) which is a core part of the JDK which replaces joda library project.

Is Joda time deprecated?

So the short answer to your question is: YES (deprecated).

What is Joda time format?

Joda-Time provides a comprehensive formatting system. There are two layers: High level - pre-packaged constant formatters. Mid level - pattern-based, like SimpleDateFormat.

What is Joda time package?

Joda-Time is an API created by joda.org which offers better classes and having efficient methods to handle date and time than classes from java. util package like Calendar, Gregorian Calendar, Date, etc. This API is included in Java 8.0 with the java.


1 Answers

There is no good reason to use DateMidnight. LocalDate is the better option. Thats because midnight does not occur once a year in certain time-zones, completely messing up the usability of the class, and creating bugs in applications.

The constructor was fixed to avoid the worst problem, however seeing a DateMidnight object with the internal millisecond value pointing at 01:00 isn't exactly great.

like image 163
JodaStephen Avatar answered Sep 28 '22 17:09

JodaStephen