Java 101: Catching up with the Java Date and Time API

Get to know the java.time classes you're most likely to use in Java 8

Page 6 of 7

Getter methods for LocalDate, LocalTime, and LocalDateTime

Each of LocalDate, LocalTime, and LocalDateTime presents various getter methods for returning values such as year, day-of-month, hour, and minute. Listing 5 demonstrates a few of these methods.

Listing 5. HumanTimeDemo.java (version 2)

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

public class HumanTimeDemo
{
   public static void main(String[] args)
   {
      LocalDateTime localDateTime = LocalDateTime.now();
      System.out.printf("Date-time: %s%n", localDateTime);
      System.out.printf("Day of year: %d%n", localDateTime.getDayOfYear());
      LocalDate localDate = localDateTime.toLocalDate();
      LocalTime localTime = localDateTime.toLocalTime();
      System.out.printf("Date: %02d-%02d-%02d%n", localDate.getYear(),
                        localDate.getMonthValue(), localDate.getDayOfMonth());
      System.out.printf("Time: %02d:%02d:%-2d%n", localTime.getHour(),
                        localTime.getMinute(), localTime.getSecond());
   }
}

Note that Listing 5 also demonstrates LocalDateTime's LocalDate toLocalDate() and LocalTime toLocalTime() methods for returning the local date and time components of a local date-time object.

Compile Listing 5 and run this application. Your output should be similar to what's shown below:

Date-time: 2013-03-23T19:35:53.154
Day of year: 82
Date: 2013-03-23
Time: 19:35:53

Manipulating local date, time, and date-time instances

LocalDate, LocalTime, and LocalDateTime declare several methods for manipulating their instances. Because these classes are immutable, their instances are not affected. Instead, copies of the instances with manipulated values are returned.

ANSI SQL date and time types

ANSI SQL defines several date and time types. LocalDate corresponds to the SQL DATE type, LocalTime corresponds to the SQL TIME type, and LocalDateTime corresponds to the SQL TIMESTAMP type.

One way to manipulate local dates, times, and date-times is to call any of their with-prefixed methods. Any of these methods will return a copy of the given object, because the core classes are immutable. (This is also why there are no setter methods.)

LocalDateTime withYear(int year), for example, returns a copy of a given LocalDateTime object with the year field set to year. The time doesn't affect the calculation and will be the same in the result.

You can also modify multiple fields by calling various plus-prefixed and minus-prefixed methods. For example, LocalDateTime minusWeeks(long weeks) subtracts the number of weeks from the current local date-time, which can affect the month and year fields.

Finally, the Date and Time API provides adjusters, which are strategies (as in the Strategy design pattern) for adjusting temporal objects. Adjusters externalize the process of adjustment, permitting different approaches, such as setting the date to the last day of the month.

Adjusters are described by the java.time.temporal.TemporalAdjuster interface. You can create your own adjusters (an example of Date and Time's extensibility) or obtain a predefined adjuster from the java.time.temporal.Adjusters class (one example being static TemporalAdjuster lastDayOfMonth()). Once you have an adjuster, pass it to a with() method such as LocalDateTime's LocalDateTime with(TemporalAdjuster adjuster) method.

Instant and adjusters

Instant declares an Instant with(TemporalAdjuster adjuster) method that lets you obtain a copy that's been modified by an adjuster. However, you'll have to create your own adjuster, because none of the predefined adjusters in the Adjusters class can be used with Instant.

Listing 6 demonstrates three approaches for obtaining a modified copy of a LocalDateTime object.

Listing 6. HumanTimeDemo.java (version 3)

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;

import static java.time.temporal.Adjusters.*;

public class HumanTimeDemo
{
   public static void main(String[] args)
   {
      LocalDateTime localDateTime = LocalDateTime.now();
      System.out.printf("Date-time: %s%n", localDateTime);
      System.out.printf("Date-time: %s%n", localDateTime.withYear(2012));
      System.out.printf("Date-time: %s%n", localDateTime.minusWeeks(3));
      System.out.printf("Date-time: %s%n", 
                        localDateTime.with(lastDayOfMonth()));
      LocalDate localDate = LocalDate.of(2010, 12, 1);
      LocalTime localTime = LocalTime.of(10, 15);
      localDateTime = localDateTime.with(localDate).with(localTime);
      System.out.printf("Date-time: %s%n", localDateTime);
   }
}

Listing 6 shows that you can use core classes such as LocalDate and LocalTime as adjusters, because most core classes implement the TemporalAdjuster interface.

Compile Listing 6 and run this application. Your output should be similar to the following:

Date-time: 2013-03-23T19:36:29.190
Date-time: 2012-03-23T19:36:29.190
Date-time: 2013-03-02T19:36:29.190
Date-time: 2013-03-31T19:36:29.190
Date-time: 2010-12-01T10:15
| 1 2 3 4 5 6 7 Page 6