Java Data Type How to - Create period of time in year and month








Question

We would like to know how to create period of time in year and month.

Answer

import java.time.Period;
/*from w  ww.j  av  a  2s. com*/
public class Main {

  public static void main(String[] args) {
    int years = 3;
    int months = 6;
    Period time = Period.ofYears(years).withMonths(months);

    System.out.println(time.getYears());
    System.out.println(time.getMonths());
  }
}

The code above generates the following result.