Home Tutorials Training Consulting Books Company Contact us


Get more...

Java Date and Time API. This article explains the date and time API introduced in Java 8.

1. Java 8 Date and Time API introduction

The Java language provides direct support for time-based objects. The Java 8 release contained a new API based on immutable-value classes, which are thread-safe. These classes provide a fluent API for constructing instances of them.

The java.time.LocalDate and the java.time.LocalTime classes provide a representation of date and time without timezones. They represent date and time from the context of an observer, such as a calendar on a desk or a clock on your wall.

java.time.LocalDateTime represents both a date and a time.

The following snippet demonstrates the usage these classes.

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAdjusters;

public class ExampleLocalDateandTimeCreation {
    public static void main(String[] args) {
        // The current date and time
        LocalDateTime dateTime = LocalDateTime.now();
        // from values
        LocalDate d1 = LocalDate.of(2015, Month.JULY, 13);

        // construct time object based on hours and minutes
        LocalTime t1 = LocalTime.of(17, 18);
        // create time object based on a String
        LocalTime t2 = LocalTime.parse("10:15:30");

        // Get the time or date from LocalDateTime
        LocalDate date = dateTime.toLocalDate();
        Month month = dateTime.getMonth();
        int day = dateTime.getDayOfMonth();
        int minute = dateTime.getMinute();
        
        
        // Perform operations on these objects will always return a new object
        // as these objects are immutable
        
        LocalDateTime updatedDate = dateTime.withDayOfMonth(13).withYear(2015);
        LocalDateTime plusYears = updatedDate.plusDays(25).plusYears(2);
        
        // the API also allow to use Adjusters for the API,
        // for example the following will set the day to the last day in the monthd
        LocalDateTime newDate = dateTime.with(TemporalAdjusters.lastDayOfMonth());
        
        // You can also truncate certain time units, e.g., remove the seconds from a time 
        // object
        LocalTime truncatedSeconds = t2.truncatedTo(ChronoUnit.SECONDS);
    }
}

The java.time.Duration class can be used to describe durations.

import java.time.Duration;

public class ExampleDuration {
public static void main(String[] args) {
    // define a duration of 5 hours
    Duration duration = Duration.ofHours(5);
    // add 20 minutes
    Duration plusMinutes = duration.plusMinutes(20);
}
}

To calculate differences between times you can use the ChronoUnit class.

import java.time.Instant;
import java.time.temporal.Temporal;
import java.time.temporal.ChronoUnit;

Instant previous, current, gap;

current = Instant.now();
if (previous != null) {
    gap = ChronoUnit.MILLIS.between(previous,current);
}

2. Parsing and formatting Dates and Times

The Date and Time classes provide the parse method for parsing a String. They also provide the format method for formating for output.

import java.time.LocalDate;
import java.time.Month;
import java.time.format.DateTimeFormatter;

public class ExampleFormatter {
    public static void main(String[] args) {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM d yyyy");
        // use this format to get always two digits for the day
        DateTimeFormatter f1 = DateTimeFormatter.ofPattern("MMM dd yyyy");
        LocalDate date = LocalDate.of(2015, Month.JULY, 1);
        System.out.println(date.format(formatter));
        System.out.println(date.format(f1));
        LocalDate d2 = LocalDate.of(2015, Month.JULY, 15);
        System.out.println(d2.format(formatter));
    }
}

3. Date and Time resources