tl;dr
OffsetDateTime.of( 2018 , 1 , 23 , 12 , 34 , 56 , 0, ZoneOffset.UTC )
java.time
The modern approach uses the java.time classes.
Unlike the troublesome legacy date-time classes, the java.time classes use sane numbering:
2018
means the year 2018. (No crazy math with 1900.)
- 1-12 for months January-December. (Not silly 0-11.)
- 1-7 for Monday-Sunday per ISO 8601 standard definition of week. (No varying by locale.)
The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
You a one-liner if you wish, if parsing a string.
Instant instant = Instant.parse( "2018-01-23T12:34:56Z" ) ;
While Instant
is a basic building-block class for java.time, the OffsetDateTime
class is more flexible. The offset-from-UTC of UTC itself is defined as a constant for your convenience.
OffsetDateTime odt = OffsetDateTime.of( 2018 , 1 , 23 , 12 , 34 , 56 , 0, ZoneOffset.UTC ) ;
Personally, I prefer using pieces.
In place of a mere integer for month, you may specify a Month
enum object.
LocalDate ld = LocalDate.of( 2018 , Month.JANUARY , 23 ) ; // Date-only, without time-of-day.
LocalTime lt = LocalTime.of( 12 , 34 , 56 ) ; // Time-of-day, without date.
ZoneOffset offset = ZoneOffset.UTC ;
OffsetDateTime odt = OffsetDateTime.of( ld , lt , offset ) ;
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.
Using a JDBC driver compliant with JDBC 4.2 or later, you may exchange java.time objects directly with your database. No need for strings nor 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.