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 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

  • 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