Period

Description

A period is a span of time in term of years, months, and days.

Negative periods are supported.

A duration is also a span of time measured in terms of seconds and nanoseconds.

A duration represents an exact number of nanoseconds which is for machine. A period is more for human.

1 day, 2 months, 3 days, 4 months and 5 days are all examples of periods. 2 month period may mean different number of days depending on different months.

Example

We can use the following 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 code shows how to create Period.


import java.time.Period;
/*from  w  ww  .ja  v  a  2  s.  c  om*/
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(2);  // 2 days
    Period p3 = Period.ofMonths(-3); // -3 months
    Period p4 = Period.ofWeeks(3); // 3 weeks 
    System.out.println(p1);
    System.out.println(p2);
    System.out.println(p3);
    System.out.println(p4);

  }
}

The code above generates the following result.

Example 2

Additions, subtractions, multiplications, and negation operations are supported by Period.

The division operation performs an integer division, for example, 7 divided by 3 is 2.

The following code shows how to use the operations on periods.


import java.time.Period;
//w w  w .ja va2s. c o m
public class Main {
  public static void main(String[] args) {
    Period p1  = Period.ofDays(15);
    System.out.println(p1);
    Period p2  = p1.plusDays(12);
    System.out.println(p2);
    Period p3  = p1.minusDays(12);
    System.out.println(p3);
    Period p4  = p1.negated();
    System.out.println(p4);
    Period p5  = p1.multipliedBy(3);
    System.out.println(p5);
  }
}

The code above generates the following result.

Example 3

Period plus() adds one period to another period.

Period minus() subtracts one period from another period.

Period normalized() method normalizes the years and months. The method ensures that the month value stays within 0 to 11. A period of "2 years and 16 months" is normalized to "3 years and 4 months."


import java.time.Period;
// w  w  w  .  ja v  a2  s . c  o  m
public class Main {

  public static void main(String[] args) {
    Period p1  = Period.of(2, 3, 5); 
    Period p2  = Period.of(1, 15,   28);
    System.out.println(p1); 
    System.out.println(p2);
    System.out.println(p1.minus(p2));
    System.out.println(p1.plus(p2));
    System.out.println(p1.plus(p2).normalized()); 
  }
}

The code above generates the following result.





















Home »
  Java Date Time »
    Tutorial »




Java Date Time Tutorial