Prior to the Java 8,
the Java date and time was defined by the
java.util.Date
,
java.util.Calendar
, and
java.util.TimeZone
classes, as well as their subclasses,
such as java.util.GregorianCalendar
.
The legacy date time API is defined in java.util
package while
the new Java 8 date time API is defined in java.time
package.
JDK 8 date time API defined several methods
to convert between java.util
and java.time
objects.
The following code shows how to convert Date to Instant back and forth.
import java.time.Instant; import java.util.Date; //from www . ja v a 2s .c o m public class Main { public static void main(String[] args) { Date dt = new Date(); System.out.println("Date: " + dt); Instant in = dt.toInstant(); System.out.println("Instant: " + in); Date dt2 = Date.from(in); System.out.println("Date: " + dt2); } }
The code above generates the following result.
We can GregorianCalendar to a ZonedDateTime, which can be converted to any other classes in the new Date-Time API.
We can convert an Instant to a ZonedDateTime then convert
ZonedDateTime to a GregorianCalendar
with from()
method from GregorianCalendar.
The following code shows how to convert a GregorianCalendar to a ZonedDateTime and vice versa.
import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; import java.time.OffsetDateTime; import java.time.OffsetTime; import java.time.ZoneId; import java.time.ZonedDateTime; import java.util.GregorianCalendar; import java.util.TimeZone; //from www . j ava 2 s . co m public class Main { public static void main(String[] args) { GregorianCalendar gc = new GregorianCalendar(2014, 1, 11, 15, 45, 50); LocalDate ld = gc.toZonedDateTime().toLocalDate(); System.out.println("Local Date: " + ld); LocalTime lt = gc.toZonedDateTime().toLocalTime(); System.out.println("Local Time: " + lt); LocalDateTime ldt = gc.toZonedDateTime().toLocalDateTime(); System.out.println("Local DateTime: " + ldt); OffsetDateTime od = gc.toZonedDateTime().toOffsetDateTime(); System.out.println("Offset Date: " + od); OffsetTime ot = gc.toZonedDateTime().toOffsetDateTime().toOffsetTime(); System.out.println("Offset Time: " + ot); ZonedDateTime zdt = gc.toZonedDateTime(); System.out.println("Zoned DateTime: " + zdt); ZoneId zoneId = zdt.getZone(); TimeZone timeZone = TimeZone.getTimeZone(zoneId); System.out.println("Zone ID: " + zoneId); System.out.println("Time Zone ID: " + timeZone.getID()); GregorianCalendar gc2 = GregorianCalendar.from(zdt); System.out.println("Gregorian Calendar: " + gc2.getTime()); } }
The code above generates the following result.