Date and Time API

11/22/08

Permalink 05:58:06 pm, by admin Email , 622 words, 1473 views   English (US)
Categories: Java

Date and Time API

The Date and Time API, also known as JSR 310, aims to provide the Java platform with a proper API for working with times. It is based on Joda-Time (Stephen Colebourne is spec lead for JSR 310 and is lead-developer for the Joda-Time project).
The API intends to fix the issues related to the original Date and Calendar classes, such as:

  • Date and calendar are mutable, which complicates multi-threaded applications,
  • Months start from 0,
  • One cannot format a Calendar directly (you need to format a date and supply the correct time-zone separately),
  • A Date-objects is not representing a date, but a date AND time,
  • DateFormatters are not thread safe
  • etc…

The following are some examples:

Code:

static void createZonedDateTimeFromCurrent() {
    Clock clk = Clock.system();
    ZonedDateTime zdt = clk.currentZonedDateTime();
    print(zdt);
    print(zdt.withZoneSameInstant(TimeZone.UTC));
    print(zdt.withZoneSameLocal(TimeZone.UTC));
}

This creates a ZonedDateTime from a clock that returns the current time. A ZonedDateTime is a real instant in time: it has a date, a time and a zone. The clock object is useful, especially for unit-tests: you could supply your own clock to unittests, for instance to simulate the switch to year 2000. The method names to create derivatives from the zdt object are a bit cryptic at first, but the first creates a new ZoneDateTime object for the same instant in time but in a different timezone, whereas the second uses the same wall-clock time (hours/minutes) but in a different timezone.

Code:

static void simpleManipulations() {
    Clock clk = Clock.system();
    ZonedDateTime zdt = clk.currentZonedDateTime();
    print(zdt.plusDays(1));
    print(zdt.plusHours(-1));
    print(zdt.plus(Period.hours(-1)));
    print(zdt.withTime(0, 0));
    print(zdt.toLocalDate().minusWeeks(1));
}

These are some simple manipulations. They read easily, except perhaps for the plusHours(-1): minusHours(1) would have made more sense, but given the large number of methods already in the ZonedDateTime class, I assume this is the sensible way. The last line extracts a LocalDateObject from the ZonedDateTime, which is used to represent just a date (and it does have minusXXX methods, plus a notion of weeks).

Code:

static void hourDetermination() {
    ZonedDateTime from, to;
    LocalDateTime okt26 = LocalDateTime.dateMidnight(2008, 10, 26);
    from = ZonedDateTime.dateTime(okt26,
               TimeZone.timeZone("Europe/Amsterdam"));
    to = from.plusDays(1);
    Duration d = Duration.durationBetween(from, to);
    System.out.println(d.getSeconds() / 60 / 60);
}

the above code calculates the number of hours on last October 26th, when the switch from summer to winter time occurred in the Netherlands. It creates two instants (or ZonedDateTimes) from a LocalDate object. A Duration is an object holding an exact time span: this contrasts with a Period object, which holds a time difference in human time-units: for the above date, the Period would be one day, but the duration is 25 x 60 x 60 seconds.

Code:

static boolean isMeeting() {
   LocalDate date = Clock.system().today();
   DateMatcher matcher = DateMatchers.dayOfWeekInMonth(3,
                          DayOfWeek.THURSDAY);
   return matcher.matchesDate(date);
}

This shows a simple date matcher: many matchers are provided in the DateMatchers class. This naming convention is used throughout the API: if there are implementations for some interface, there will probably be a class with the name of the interface postfixed with an ’s’, containing static methods that supply instances of the class.

The API provides more functionality, like date adjusters, date resolvers, input and output (thread-safe this time!). Some integration with the original date and calendar classes is also provided by having those implement the new interfaces.

There is much more to be learnt on this new API, but I’d like to refer you to the reference for that. I think this API is a valuable replacement that reduces the amount of problems when working with times.

References:
https://jsr-310.dev.java.net/ - the project page.
http://today.java.net/pub/a/today/2008/09/18/jsr-310-new-java-date-time-api.html - a well written introduction to the API.
JavaOne session TS-6578 - the session on JSR 310 at JavaOne 2008

Pingbacks:

No Pingbacks for this post yet...

Floris' Blog

Personal blog on my interests.

September 2010
Sun Mon Tue Wed Thu Fri Sat
 << <   > >>
      1 2 3 4
5 6 7 8 9 10 11
12 13 14 15 16 17 18
19 20 21 22 23 24 25
26 27 28 29 30    

Search

Categories

Misc

XML Feeds

What is RSS?

Who's Online?

  • Guest Users: 1

powered by b2evolution free blog software