121
public static void newSpecifiedDate() {
LocalDate date = LocalDate.of(2021, Month.NOVEMBER, 12);
System.out.println("Date from specified date: " + date);
}
The main is:
public static void main(String[] args) {
newSpecifiedDate();
}
Here’s the result.
Date from specified date: 2021-11-12
How It Works
The LocalDate.of() method accepts three values as parameters. Those parameters
represent the year, month, and day. The year parameter is always treated as an int value.
The month parameter can be presented as an int value, corresponding to an enum
representing the month. The Month enum returns
an int value for each month, with
JANUARY returning a 1 and DECEMBER returning a 12. Therefore, Month.NOVEMBER
returns an 11. A Month object could also be passed as the second parameter instead of
an int value. Lastly, the day of the month is specified by passing
an int value as the third
parameter to the of() method.
4-9. Obtaining a Year-Month-Day Date Combination
Problem
You want to obtain a specified date’s year, year-month, or month.
Solution 1
To obtain the
year-month of a specified date, use the java.time.YearMonth class.
This class represents the month of a specific year. In the following lines of code,
the YearMonth object obtains the year and month of the current date and another
specified date.
Chapter 4 Numbers aNd dates
122
public static void obtainYearMonth() {
YearMonth yearMo = YearMonth.now();
System.out.println("Current Year and month:" + yearMo);
YearMonth specifiedDate = YearMonth.of(2021, Month.NOVEMBER);
System.out.println("Specified Year-Month: " + specifiedDate);
}
Here is the result.
Current Year and month:2021-10
Specified Year-Month: 2021-11
Do'stlaringiz bilan baham: