Use Instant
, replacement for java.util.Date
.
Instant.now() // Capture current moment as seen in UTC.
If you must have a Date
, convert.
java.util.Date.from( Instant.now() )
The java.util.Date & .Calendar classes have been supplanted by the java.time framework built into Java 8 and later. The new classes are a tremendous improvement, inspired by the successful Joda-Time library.
The java.time classes tend to use static factory methods rather than constructors for instantiating objects.
To get the current moment in UTC time zone:
Instant instant = Instant.now();
To get the current moment in a particular time zone:
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( zoneId );
If you must have a java.util.Date for use with other classes not yet updated for the java.time types, convert from Instant
.
java.util.Date date = java.util.Date.from( zdt.toInstant() );
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.