Java 17 Recipes


-8. Obtaining a Date Object Given Date Criteria


Download 3.2 Mb.
Pdf ko'rish
bet73/245
Sana02.06.2024
Hajmi3.2 Mb.
#1839910
1   ...   69   70   71   72   73   74   75   76   ...   245
Bog'liq
Java 17 Recipes

4-8. Obtaining a Date Object Given Date Criteria
 Problem
You want to obtain a Date object, given a year-month-day specification.
 Solution
Invoke the LocalDate.of() method for the year, month, and day you want to obtain the 
object. For example, suppose that you want to obtain a Date object for a specified date 
in November of 2021. You could pass the date criteria to the LocalDate.of() method, as 
demonstrated in the following lines of code.
Chapter 4 Numbers aNd dates


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

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   69   70   71   72   73   74   75   76   ...   245




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling