Newsletter sign-up
View all newsletters

Enterprise Java Newsletter
Stay up to date on the latest tutorials and Java community news posted on JavaWorld

Sponsored Links

Optimize with a SATA RAID Storage Solution
Range of capacities as low as $1250 per TB. Ideal if you currently rely on servers/disks/JBODs

Java 101: The next generation: It's time for a change

Catching up with the Java Date and Time API

  • Print
  • Feedback

Page 3 of 7

 

Instant and Duration

The java.time package's Instant and Duration classes provide a machine view of the timeline, which is a single, continually incrementing number. Instant stores a point in time relative to the epoch; Duration stores a time-based amount of time, like 25.8 seconds.

Use cases for machine time classes

You could use Instant to record event timestamps and Duration to record animation cycle lengths.

Instant stores an instant relative to the epoch as a number of seconds in a long integer field and as a number of nanoseconds beyond the last second (i.e., nanosecond-of-second) in an integer field. Duration stores a time-based amount of time similarly.

Instantiating Instant and Duration

Instant and Duration declare a number of constants that describe pre-created Instants and Durations:

  • EPOCH is an Instant representing the epoch.
  • MAX is an Instant that identifies the largest possible (i.e., far future) instant.
  • MIN is an Instant that identifies the smallest possible (i.e., far past) instant.
  • ZERO is a Duration representing a duration of zero.

Instant and Duration also declare several fluent factory methods for instantiating these classes:

  • Instant now() returns an Instant from the system clock using the UTC (Coordinated Universal Time) time zone.
  • Instant ofEpochSecond(long epochSecond) returns an Instant identifying the instant epochSecond seconds past the epoch. The nanosecond-of-second field is set to zero.
  • Instant parse(CharSequence text) returns an Instant from an ISO-8601 text string such as 2007-12-03T10:15:30Z. If the string doesn't represent a valid instant in UTC, this method throws an instance of the java.time.format.DateTimeParseException runtime exception class. (ISO-8601 specifies T as the time designator that precedes the time components in the formatted string representation, and it specifies Z to indicate UTC.)
  • Duration ofSeconds(long seconds) returns a Duration identifying seconds seconds and setting the nanosecond-of-second field to 0.
  • Duration parse(CharSequence text) returns a Duration from an ISO-8601 text string such as PT3M20S. (ISO-8601 specifies P -- which historically stood for "period" -- to signify a duration. It also specifies M to indicate minutes and S to indicate seconds.)

Machine time classes: A demo

Listing 1 demonstrates the above-listed constants and fluent factory methods in a simple application that outputs constant values and the results of calls to these methods.

Listing 1. MachineTimeDemo.java (version 1)

import java.time.Duration;
import java.time.Instant;

public class MachineTimeDemo
{
   public static void main(String[] args)
   {
      System.out.printf("EPOCH = %s%n", Instant.EPOCH);
      System.out.printf("MAX = %s%n", Instant.MAX);
      System.out.printf("MIN = %s%n", Instant.MIN);

      System.out.printf("Now = %s%n", Instant.now());
      System.out.printf("50 seconds past epoch = %s%n",
                        Instant.ofEpochSecond(50));
      System.out.printf("Parsed = %s%n",
                        Instant.parse("2007-12-03T10:15:30Z"));

      System.out.printf("ZERO = %s%n", Duration.ZERO);

      System.out.printf("30-second duration = %s%n",
                        Duration.ofSeconds(30));
      System.out.printf("Parsed = %s%n",
                        Duration.parse("PT3M20S"));     
   }
}

Note in Listing 1 that Instant, Duration (and other java.time classes) provide a toString() method that returns a string representation of the object's value in ISO-8601 format. This method is automatically called by System.out.printf().

If you compile this application (javac MachineTimeDemo.java) and run it (java MachineTimeDemo) your output should be similar to what's shown below:

EPOCH = 1970-01-01T00:00Z
MAX = +1000000000-12-31T23:59:59.999999999Z
MIN = -1000000000-01-01T00:00Z
Now = 2013-03-24T00:33:20.986Z
50 seconds past epoch = 1970-01-01T00:00:50Z
Parsed = 2007-12-03T10:15:30Z
ZERO = PT0S
30-second duration = PT30S
Parsed = PT3M20S

  • Print
  • Feedback

Resources

Recommended

  • "All I want for Java 8 ..." (Dusting Marx, April 2011): A developer's annotated wish list for Java 8.
  • "How badly do we want a new Java Date and Time API?" (Dustin Marx, March 2012) surveys developer opinion about the Java date and time infrastructure prior to Java 8.
  • JavaWorld syndicated blogger Ted Neward explains why he believes that Java 8 will be a game changer for Java development.
  • Martin Fowler discusses precision in his blog post about Time Point implementation in computer programming (MartinFowler.com, March 2004).

More about the Java Date and Time API

  • JSR 310: Date and Time API: The specification is the definitive source for learning about the new types in java.time.
  • Also visit the OpenJDK Project ThreeTen homepage, which includes a link to JSR 310's Sourceforge repository and a current release timeline.
  • JSR 310 co-lead and Joda Time creator Stephen Colebourne has written extensively on his blog about the relationship between Joda Time and the new Java Date and Time APIs.
  • In "From Instants to Eras, the Future of Java" (JW Blogs, October 2012) Dustin Marx reports from JavaOne 2012 on the potential impact of the new Date and Time API, as well as some of its core concepts.

Popular articles in the Java 101 series