tl;dr
- Use types appropriate to your values:
LocalDate
- Never use the terrible legacy class
java.util.Date
- Learn to use converters/adapters in your Java⇔JSON serialization framework
- Use standard ISO 8601 formats for date-time values whenever possible
Details
Use appropriate types to represent your data values. For a date-only value, without a time-of-day and without a time zone, the appropriate type is LocalDate
.
Never use java.util.Date
. That terrible class was supplanted years ago by the java.time classes.
As for generating textual representations in JSON, that is an entirely separate issue.
JSON has very few data types and none of them are date-time related. So whatever JSON output you are getting for your LocalDate
input is a function of your particular Java-to-JSON library you are using. You do not divulge what library, so we cannot provide further assistance.
I can tell you that there is an established practical international standard for representing date-time values: ISO 8601. I strongly suggest always using these standard formats when serializing your date-time values to text.
For a date-only value, the standard format is YYYY-MM-DD such as 2018-01-23
.
The java.time classes use these standard formats by default when parsing/generating strings.
LocalDate.parse( "2018-01-23" ) ;
And:
myLocalDate.toString()
2018-01-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
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
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.