Java Period class

Introduction

We can use the following constructor to create object of 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)
import java.time.Period;

public class Main {
  public static void main(String[] args) {
    Period p1 = Period.of(1, 2, 3); // 1 years, 2 months, and 3 days
    Period p2 = Period.ofDays(42);  // 42 days
    Period p3 = Period.ofMonths(-3); // -3 months
    Period p4 = Period.ofWeeks(3); // 3 weeks 
    System.out.println(p1);//  ww w.ja  v a  2s.  co m
    System.out.println(p2);
    System.out.println(p3);
    System.out.println(p4);

  }
}

Do some calculation on Period

import java.time.Period;

public class Main {
  public static void main(String[] args) {
    Period p1  = Period.ofDays(15);
    System.out.println(p1);/*from  ww w  .  j av  a 2  s . com*/
    
    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);
    
  }
}

Calculation between two Period objects


import java.time.Period;

public class Main {
  public static void main(String[] args) {
     Period p1  = Period.of(2, 3, 5); 
     Period p2  = Period.of(42, 42, 42);
     System.out.println(p1); /*w  w  w.  j a v  a  2  s . c  o  m*/
     System.out.println(p2);
     System.out.println(p1.minus(p2));
     System.out.println(p1.plus(p2));
     System.out.println(p1.plus(p2).normalized()); 

  }
}



PreviousNext

Related