Java Time API in JDK 8

  • Post author:
  • Post category:Java

The Java Time API is finally part of the early access releases of JDK 8. Most of us have been using Joda-Time, and soon we will have a nice Date and Time API built in Java. Here we’ll download JDK 8 build 75 and play around with the new API. If you wish to use an IDE with JDK 8, you can use the latest versions of IntelliJ or Netbeans. Eclipse does not support JDK 8 at this time.

Here are a few code snippets to help us quickly understand the new API. Note the package is java.time, and not javax.time.

Instant. An instantaneous point on the time-line. This is the closest equivalent to java.util.Date.

	Instant instant = Instant.now();
	System.out.println(instant.toString()); // prints 2013-02-08T18:47:15.937Z

LocalDate. A date without a time-zone in the ISO-8601 calendar system, such as 2000-12-31.

	LocalDate localDate = LocalDate.now();
	System.out.println(localDate.toString()); // prints 2013-02-08

LocalTime. A time without time-zone in the ISO-8601 calendar system, such as 12:30:00.

	LocalTime localTime = LocalTime.now();
	System.out.println(localTime.toString()); // prints 13:47:16.734

LocalDateTime. A date-time without a time-zone in the ISO-8601 calendar system, such as 2000-12-31T12:30:00.

	LocalDateTime localDateTime = LocalDateTime.now();
	System.out.println(localDateTime.toString()); // prints 2013-02-08T13:47:16.734

ZonedDateTime. A date-time with a time-zone in the ISO-8601 calendar system, such as 2000-12-31T12:30:00-05:00 America/New_York. This is the closest equivalent to java.util.GregorianCalendar.

	ZonedDateTime zonedDateTimeNow = ZonedDateTime.now();
	System.out.println(zonedDateTimeNow.toString()); // prints 2013-02-08T14:00:13.796-05:00[America/New_York]

Clock. A clock providing access to the current instant, date and time using a time-zone. If injected in code, simplifies testing as you can change the application clock without changing the system clock.

	Clock clock = Clock.systemUTC();
	long millis = clock.millis();
	System.out.println(millis);	// prints 1360348116109

Duration. A duration between two instants on the time-line, not tied to an instant.

	Duration duration = Duration.ofHours(1);
	System.out.println(duration.toString()); // prints PT3600S

Period. A period of time, in units meaningful to humans, such as ‘1 Year, 2 Months and 3 Days’.

	int year = 1, month = 2, days = 3;
	Period period = Period.ofDate(year, month, days);
	System.out.println(period.toString()); // prints P1Y2M3D

ZoneId. A time-zone ID, such as America/New_York.

	ZoneId zoneId = ZoneId.systemDefault();
	System.out.println(zoneId.toString()); // prints America/New_York

ZoneOffset. A time-zone offset from Greenwich/UTC, such as -05:00.

	ZoneOffset zoneOffset = ZoneOffset.ofHours(1);
	System.out.println(zoneOffset.toString()); // prints +01:00

Please note the Java API is still expected to change, until the official release of JDK 8 in October 2013.