2

I am using a java.sql.Date to store a date field in one of my domain objects. This field is mapped to a MySQL DATE column. When I try to serialize this field to JSON through Jackson, Jackson does not seem to account for daylight savings time.

Here is what the field looks like in my domain object:

@JsonFormat(shape = JsonFormat.Shape.STRING, pattern = "yyyy-MM-dd", timezone = "EST")
private Date date;

As you can see, Jackson has been instructed to interpret the timezone as EST. My MySQL database is also using the EST timezone:

SHOW VARIABLES LIKE '%zone';
Output:
system_time_zone | EST
time_zone        | SYSTEM

My trouble is that for the dates between daylight savings time start and end, Jackson returns one day less than the date stored in the database. I am assuming this is because Jackson is not considering daylight savings.

I arrived at this conclusion by trying to change the date's format from yyyy-MM-dd to yyyy-MM-dd HH:mm:ss in the Java field. I noticed that the server returned something like 2017-03-13 00:00:00, but Jackson serialized it to 2017-03-12 23:00:00 (one hour less, which is how much EST time is affected by daylight savings).

Is there any way to overcome this problem? Also, is java.sql.Date the right type to use, considering it does not have a time counterpart? I have been considering using java.time.LocalDate instead, but I am yet to see if it will be successful.

Thanks in advance!

lebowski
  • 1,031
  • 2
  • 20
  • 37
  • 1
    Also noted that using `java.time.LocalDate` seemed to solve the issue. Not sure why. – lebowski Mar 04 '19 at 19:45
  • 1
    I don't think Jackson is to blame here, I suspect your MySQL database or specifically the driver you're using to connect to the database. That driver is responsible of converting the value from the database into `java.sql.Date` and it uses (as far as I remember) your current/local timezone for that. I had similar issues with MySQL, the standard drivers and daylight savings, so I switched to UTC to avoid all these issues. – Tom Mar 04 '19 at 19:59
  • 1
    Well, technically Jackson could also be blamed, because `2017-03-13 00:00:00` doesn't exist in EST, only in EDT, right? – Tom Mar 04 '19 at 20:01
  • 1
    The *real* blame belongs to `java.sql.Date` for carrying a time-of-day while pretending to be a date-only. – Basil Bourque Mar 04 '19 at 20:19
  • @Tom That's right, `2017-03-13 00:00:00` is an EDT time. It could be a driver issue as you said, and switching to UTC makes sense. – lebowski Mar 04 '19 at 20:26
  • @BasilBourque I don't think `java.sql.Date` carries time inherently, as far as I can tell. I started seeing `2017-03-13 00:00:00` instead of just `2017-03-13` after modifying Jackson's `@JsonIgnore` annotation to format the date as `yyyy-MM-dd HH:mm:ss` instead of `yyyy-MM-dd`. So this seems to be something internal to Jackson which is trying to add a timestamp to a field which by it's definition is not supposed to have a timestamp. – lebowski Mar 04 '19 at 20:29
  • @lebowski Yes, `java.sql.Date` absolutely *does* carry a time-of-day in UTC. [See the JavaDoc](https://docs.oracle.com/en/java/javase/11/docs/api/java.sql/java/sql/Date.html). Inherits from `java.util.Date`. I added a quote of that doc to my Answer. – Basil Bourque Mar 04 '19 at 20:38
  • @BasilBourque You're right, I added that comment before reading your answer. All makes sense, thanks for the detailed explanation! – lebowski Mar 04 '19 at 20:39

1 Answers1

5

tl;dr

  • Never use java.sql.Date nor java.util.Date.
    Use only java.time classes.
  • For a date-only value, use LocalDate.
    You will see only stable values, without impact from Daylight Saving Time (DST).

Example:

LocalDate.parse( "2019-01-23" )

java.sql.Date is not a date

I am not sure exactly what the problem is, but I suspect it is due to your use of the terrible java.sql.Date class, and therefore moot.

The java.sql.Date class pretends to represent a date-only value, without time-of-day and without time zone. However, due to some unimaginably bad design decisions, that class extends java.util.Date. The java.util.Date class does have a time-of-day and is in UTC. Even more confusing, java.util.Date has a time zone buried in its source code without getters & setters, so it seems to not be there yet affects behavior of methods like equals. So java.sql.Date, despite its name, and despite its purpose of holding a date-only, actually does have a time-of-day set to UTC. So java.sql.Date pulls some stunts in adjusting the time-of-day which is likely the problem you are encountering. These legacy date-time classes are a big steaming pile of… oatmeal. You should never use them.

To quote the JavaDoc for the java.sql.Date class:

A thin wrapper around a millisecond value that allows JDBC to identify this as an SQL DATE value. A milliseconds value represents the number of milliseconds that have passed since January 1, 1970 00:00:00.000 GMT.

To conform with the definition of SQL DATE, the millisecond values wrapped by a java.sql.Date instance must be 'normalized' by setting the hours, minutes, seconds, and milliseconds to zero in the particular time zone with which the instance is associated.

By the way, java.sql.Timestamp is just as bad a wretched mess. It too inherits awkwardly from java.util.Date, adding a second fractional second for nanoseconds. Avoid this class too, now replaced by java.time.Instant or java.time.OffsetDateTime. Similarly, java.sql.Time is replaced by java.time.LocalTime.

java.time.LocalDate is truly a date

With the adoption of JSR 310 and JDBC 4.2, you can use the modern industry-leading java.time classes. By now, Jackson may have been updated to use java.time. If not, see this Question for links to data-type modules to handle java.time in Jackson.

Looks like your input strings are in standard ISO 8601 format, YYYY-MM-DD. The java.time classes use the standard formats by default when parsing/generating strings that represent date-time values. For a date-only use, LocalDate class which truly is a date without time-of-day, and without zone/offset. You will see stable date-values without impact from Daylight Saving Time (DST).

Parse.

LocalDate ld = LocalDate.parse( "2019-01-23" ) ;

Store.

myPreparedStatement.setObject( … , ld ) ;

Retrieve.

LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;

About LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone or offset-from-UTC.

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris France is a new day while still “yesterday” in Montréal Québec.

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any moment during runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If critical, confirm the zone with your user.

Specify a proper time zone name in the format of Continent/Region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 2-4 letter abbreviation such as EST or IST as they are not true time zones, not standardized, and not even unique(!).

ZoneId z = ZoneId.of( "America/Montreal" ) ;  
LocalDate today = LocalDate.now( z ) ;

If you want to use the JVM’s current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.

ZoneId z = ZoneId.systemDefault() ;  // Get JVM’s current default time zone.

Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.

LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.

Or, better, use the Month enum objects pre-defined, one for each month of the year. Tip: Use these Month objects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety. Ditto for Year & YearMonth.

LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154