Java Reference
In-Depth Information
You would like to obtain the year, year-month, or month of a specified date.
Solution #1
To obtain the year-month of a specified date, use the java.time.YearMonth class.
This class is used to represent the month of a specific year. In the following lines of
code, the YearMonth object is used to obtain the year and month of the current date
and another specified date.
YearMonth yearMo = YearMonth.now();
System.out.println("Current Year and month:" + yearMo);
YearMonth specifiedDate = YearMonth.of(2000,
Month.NOVEMBER);
System.out.println("Specified Year-Month: "
+ specifiedDate);
Here's the result:
Current Year and month: 2014-12
Specified Year-Month: 2000-11
Solution #2
To obtain the month-day for the current date or a specified date, simply make use of the
java.time.MonthDay class. The following lines of code demonstrate how to ob-
tain a month-day combination.
MonthDay monthDay = MonthDay.now();
System.out.println("Current month and day: " + monthDay);
MonthDay specifiedDate = MonthDay.of(Month.NOVEMBER, 11);
System.out.println("Specified Month-Day: "
+ specifiedDate);
Here's the result:
Current month and day: --12-14
Specified Month-Day: --11-11
Search WWH ::




Custom Search