Java - Date Time Period


A period of time is an amount of time in terms of calendar fields years, months, and days.

A duration is an amount of time in terms of seconds and nanoseconds.

Negative periods are supported.

Period and Duration

A duration represents an exact number of nanoseconds, whereas a period represents an inexact amount of time.

A period is for humans what a duration is for machines.


Examples of periods are 1 day, 2 months, 5 days, 3 months and 2 days, etc.

A 2 month period may mean different number of days depending on when that period starts.

An instance of the Period class represents a period.

Use one of the following static factory methods to create a Period:

static Period of(int years, int months, int days)
static Period ofDays(int days)
static Period ofMonths(int months)
static Period ofWeeks(int weeks)
static Period ofYears(int years)

The following snippet of code creates some instances of the Period class:


import java.time.Period;

public class Main {
  public static void main(String[] args) {
    Period p1 = Period.of(2, 3, 5); // 2 years, 3 months, and 5 days
    Period p2 = Period.ofDays(25); // 25 days
    Period p3 = Period.ofMonths(-3); // -3 months
    Period p4 = Period.ofWeeks(3); // 3 weeks (21 days)
    System.out.println(p1);//w ww .j ava  2s.c  o  m


Related Topics