Java YearMonth
The Java YearMonth class is an immutable and thread-safe class that represents the combination of a year and month. The YearMonth class can be used to store information in the following format “April 2018”.
How to use
This class does not handle or represent a day, time or time-zone, Try the following examples to better understand –
Current year month example
The following example program shows how you can get the current month and year using YearMonth.
import java.time.YearMonth; public class YearMonthExample1 { public static void main(String[] args) { // Get a instance of YearMonth YearMonth yearMonth = YearMonth.now(); // Print current year and month System.out.println(yearMonth); } }
Format example
The following example program shows how you can format year and month.
import java.time.YearMonth; import java.time.format.DateTimeFormatter; public class YearMonthExample2 { public static void main(String[] args) { // Get a instance of YearMonth YearMonth yearMonth = YearMonth.now(); System.out.println("Default format: " + yearMonth); // Format year and month DateTimeFormatter formatter = DateTimeFormatter.ofPattern("MMM-yyyy"); String formatted = yearMonth.format(formatter); System.out.println("Formatted: " + formatted); } }
Fields example
The following example program shows how you can get different fields.
import java.time.YearMonth; import java.time.temporal.ChronoField; public class YearMonthExample3 { public static void main(String[] args) { // Get a instance of YearMonth YearMonth yearMonth = YearMonth.now(); System.out.println("Default format: " + yearMonth); // Get different fields int year = yearMonth.get(ChronoField.YEAR); System.out.println("Year: " + year); int monthOfYear = yearMonth.get(ChronoField.MONTH_OF_YEAR); System.out.println("Month of year: " + monthOfYear); } }