Java - Year, YearMonth, MonthDay

Introduction

A Year represents a year, for example, 2012, 2013, etc.

A YearMonth represents a valid combination of a year and a month, for example, 2012-05, 2013-09, etc.

A MonthDay represents a valid combination of a month and a day of month, for example, -12-15.

The following code shows how to use Year, YearMonth, and MonthDay Partials.

Demo

import java.time.Month;
import java.time.MonthDay;
import java.time.Year;
import java.time.YearMonth;

public class Main {
  public static void main(String[] args) {
    // Use Year//from  ww w .j  a v a  2s .c o m
    Year y1 = Year.of(2012); // 2012
    System.out.println(y1);
    Year y2 = y1.minusYears(1); // 2011
    System.out.println(y2);
    Year y3 = y1.plusYears(1); // 2013
    System.out.println(y3);
    Year y4 = Year.now(); // current year
    System.out.println(y4);
    if (y1.isLeap()) {
      System.out.println(y1 + " is a leap year.");
    } else {
      System.out.println(y1 + " is not a leap year.");
    }

    // Use YearMonth
    YearMonth ym1 = YearMonth.of(2012, Month.MAY); // 2012-05

    // Get the number of days in the month
    int monthLen = ym1.lengthOfMonth(); // 31
    System.out.println("Days in month in " + ym1 + ": " + monthLen);

    // Get the number of days in the year
    int yearLen = ym1.lengthOfYear(); // 366
    System.out.println("Days in year in " + ym1 + ": " + yearLen);

    // Use MonthDay
    MonthDay md1 = MonthDay.of(Month.DECEMBER, 25);
    System.out.println(md1);
    MonthDay md2 = MonthDay.of(Month.FEBRUARY, 29);
    System.out.println(md2);
    if (md2.isValidYear(2009)) {
      System.out.println(md2 + " occurred in 2009");
    } else {
      System.out.println(md2 + " did not occur in 2009");
    }
  }
}

Result

Related Topics