Java Date-Time Year, YearMonth, MonthDay, and Convert Year to LocalDate

Ibnu Arseno
Code Storm
Published in
2 min readNov 21, 2021

Within the new Data & Time API classes are the Year, YearMonth, and MonthDay classes. such as the name of the class Year is used to retrieve data that contains only the year, YearMonth to display year and month data, and MonthDay is used to retrieve month and date data in the month.

Photo by J Taubitz on Unsplash

why use the Year, YearMonth, and MonthDay classes? because in these classes there are methods that can be used to help us manipulate data. The default format for Year is yyyy, the default format for YearMonth is yyyy-MM, and the default format for MonthDay is — MM-dd.

Year

to display the current year data can use:

Year year = Year.now;

if you want to set the year according to what we want, you can use:

Year year = Year.of(2024);

to do parsing can use:

Year year = Year.parse(“2024”);

YearMonth

to display the current year and month data can use:

YearMonth yearMonth = YearMonth.now;

if you want to customize the year and month data according to what we want, you can use:

YearMonth yearMonth = YearMonth.of(1998, Month.JUNE);

to do parsing can use:

Year year = Year.parse(“2025-01”);

MonthDay

to display month and date data in the current month can use:

MonthDay monthDay = MonthDay.now;

if you want to custom the month and date data in the month according to what we want, you can use:

MonthDay monthDay = MonthDay.of(Month.JUNE, 20);

to do parsing can use:

MonthDay monthDay = MonthDay.parse(“--09-10”);

Convert from Year to LocalDate

If a conversion is needed from the Year data type to LocalDate, it is necessary to provide additional month data and date data, to add it can be done using atMonth, and atDay.

Year year = Year.of(2020);
YearMonth yearMonth = year.atMonth(Month.DECEMBER);
LocalDate localDate = yearMonth.atDay(30);

so the Year, YearMonth, and MonthDay classes are smaller types than LocalDate.

--

--