Java Reference
In-Depth Information
Listing 12-29.
Converting a Date to an Instant and Vice Versa
// DateAndInstant.java
package com.jdojo.datetime;
import java.util.Date;
import java.time.Instant;
public class DateAndInstant {
public static void main(String[] args) {
// Get the current date
Date dt = new Date();
System.out.println("Date: " + dt);
// Convert the Date to an Insatnt
Instant in = dt.toInstant();
System.out.println("Instant: " + in);
// Convert the Instant back to a Date
Date dt2 = Date.from(in);
System.out.println("Date: " + dt2);
}
}
Date: Sat Jan 11 14:45:02 CST 2014
Instant: 2014-01-11T20:45:02.265Z
Date: Sat Jan 11 14:45:02 CST 2014
Typically, the legacy code uses
GregorianCalendar
to store date, time, and datetime. You can convert it to a
ZonedDateTime
, which can be converted to any other classes in the new Date-Time API. The
Calendar
class provides a
toInstant()
method to convert its instance to an
Instant
. The
Calendar
class is abstract. Typically, you would have
an instance of its concrete subclass class, for example,
GregorianCalendar
. Therefore, converting an
Instant
to a
GregorianCalendar
would be a two-step process:
Instant
to a
ZonedDateTime,
•
Convert the
from()
static method of the
GregorianCalendar
class to get a
GregorianCalendar
.
The program in Listing 12-30 shows how to convert a
GregorianCalendar
to a
ZonedDateTime
and vice versa.
The program also shows how to get a
LocalDate
,
LocalTime
, etc. from a
GregorianCalendar
. You may get a little
different output because the output depends on the system's default time zone.
•
Use the
Listing 12-30.
Converting a GregorianCalendar to New Datetime Types and Vice Versa
// GregorianCalendarAndNewDateTime.java
package com.jdojo.datetime;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.OffsetDateTime;