According to the Java API, the constructor Date(year, month, day)
is deprecated. I know that I can replace it with the following code:
Calendar myCa
LocalDate.of( 2015 , Month.JUNE , 7 ) // Using handy `Month` enum.
…or…
LocalDate.of( 2015 , 6 , 7 ) // Sensible numbering, 1-12 for January to December.
The java.time framework built into Java 8 and later supplants the troublesome old classes, java.util.Date/.Calendar.
The java.time classes use immutable objects. So they are inherently thread-safe. You will have none of the thread-safety problems mentioned on the other answers.
LocalDate
This framework included a class for date-only objects without any time-of-day or time zone, LocalDate. Note that a time zone (ZoneId
) is necessary to determine a date.
LocalDate today = LocalDate.now( ZoneId.of( "America/Montreal" ) );
You can instantiate for a specific date. Note that month number is a sensible range of 1-12 unlike the old classes.
LocalDate localDate = LocalDate.of( 2015 , 6 , 7 );
Or use the enum, Month.
LocalDate localDate = LocalDate.of( 2015 , Month.JUNE , 7 );
Best to avoid the old date-time classes. But if you must, you can convert. Call new methods added to the old classes to facilitate conversions.
In this case we need to specify a time-of-day to go along with our date-only value, to be combined for a java.util.Date
object. First moment of the day likely makes sense. Let java.time determine the time of that first moment as it is not always 00:00:00.0
.
We also need to specify a time zone, as the date varies by time zone.
ZoneId zoneId = zoneId.of( "America/Montreal" );
ZonedDateTime zdt = localDate.atStartOfDay( zoneId );
An Instant
is a basic class in java.time, representing a moment on the timeline in UTC. Feed an Instant
to static method on Date to convert.
Instant instant = zdt.toInstant();
java.util.Date utilDate = java.util.Date.from( instant );
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.