Java - Date Time API

Design Principles

Classes in the Date-Time API do not provide public constructors.

You create their objects by providing static factory methods named of(), ofXxx(), and from().

Date-Time API

All classes, interfaces, and enums for the Date-Time API are in the java.time package and four of its subpackages:

  • java.time contains frequently used classes. LocalDate, LocalTime, LocalDateTime, ZonedDateTime, Period, Duration, and Instant classes are in this package. Classes in this package are based on ISO standards.
  • java.time.chrono contains classes supporting non-ISO calendar systems, for example, Hijrah calendar, ThaiBuddhist calendar, etc.
  • java.time.format contains classes for formatting and parsing dates and times.
  • java.time.temporal contains classes for accessing components of dates and times. It contains classes that acts like date-time adjusters.
  • java.time.zone contains classes supporting time zones and zone rules.

The following snippet of code creates date-time objects representing a date, a time, and a combination of them with and without a time zone:

Demo

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

public class Main {
  public static void main(String[] args) {
    LocalDate dateOnly = LocalDate.now();
    LocalTime timeOnly = LocalTime.now();
    LocalDateTime dateTime = LocalDateTime.now();
    ZonedDateTime dateTimeWithZone = ZonedDateTime.now();
    System.out.println(dateOnly);
    System.out.println(timeOnly);
    System.out.println(dateTime);
    System.out.println(dateTimeWithZone);

  }//from w  w  w  .  j av  a  2 s  . c o  m
}

Result

Useful Datetime-Related Enums

  • Month
  • DayOfWeek
  • ChronoField
  • ChronoUnit