Java 17 Recipes


-7. Obtaining the Current Date Without Time


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

4-7. Obtaining the Current Date Without Time
 Problem
You are developing an application for which you want to obtain the current date, not 
including the time, to display on a form.
 Solution
Use the Date-Time API to obtain the current date. The LocalDate class represents an ISO 
calendar in the year-month-day format. The following lines of code capture the current 
date and display it.
public static void newDate() {
LocalDate date = LocalDate.now();
System.out.println("Current Date:" + date);
}
The output is:
Current Date: 2021-11-30
 How It Works
The Date-Time API makes it easy to obtain the current date, without including other 
information. To do so, import the java.time.LocalTime class and call on its now() 
method. The LocalTime class cannot be instantiated, as it is immutable and thread-safe. 
A call to the now() method returns another LocalDate object, containing the current 
date in the year-month-day format.
Chapter 4 Numbers aNd dates


120
Another version of the now() method accepts a java.time.Clock object as a 
parameter and returns the date based on that clock. For instance, the following lines of 
code demonstrate how to obtain a Clock object that represents the system time.
public static void newDateFromClock() {
Clock clock = Clock.systemUTC();
LocalDate date = LocalDat.now(clock);
System.out.println("Date from clock: " + date);
}
The output is:
Date from clock: 2021-11-30
The main class is:
public static void main(String[] args) {
newDate();
newDateFromClock();
}
There were other ways to obtain the current date in previous releases, but usually, 
the time came with the date, and then formatting had to be done to remove the 
unneeded time digits. The new java.time.LocalDate class makes it possible to work 
with dates separate from times.

Download 3.2 Mb.

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




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