Java 17 Recipes


-10. Obtaining and Calculating Times Based on


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

4-10. Obtaining and Calculating Times Based on 
the Current Time
 Problem
You want to obtain the current time to stamp a given record. You would also like to 
perform calculations based on that time.
 Solution
Use the LocalTime class, which is part of the new Date-Time API, to obtain and display 
the current time. In the following lines of code, the LocalTime class is demonstrated.
public static void currentTime(){
LocalTime time = LocalTime.now();
System.out.println("Current Time: " + time);
}
Chapter 4 Numbers aNd dates


124
Once the time has been obtained, methods can be called against the LocalTime 
instance to achieve the desired result. In the following lines of code, there are some 
examples of using the LocalTime methods.
// atDate(LocalDate): obtain the local date and time
LocalDateTime ldt = time.atDate(LocalDate.of(2021,Month.NOVEMBER,12));
System.out.println("Local Date Time object: " + ldt);
// of(int hours, int min): obtain a specific time
LocalTime pastTime = LocalTime.of(1, 10);
// compareTo(LocalTime): compare two times. Positive
// return value returned if greater
System.out.println("Comparing times: " + time.compareTo(pastTime));
// getHour(): return hour in int value (24-hour format)
int hour = time.getHour();
System.out.println("Hour: " + hour);
// isAfter(LocalTime): return Boolean comparison
System.out.println("Is local time after pastTime? " + time.
isAfter(pastTime));
// minusHours(int): Subtract Hours from LocalTime
LocalTime minusHrs = time.minusHours(5);
System.out.println("Time minus 5 hours: " + minusHrs);
// plusMinutes(int): Add minutes to LocalTime
LocalTime plusMins = time.plusMinutes(30);
System.out.println("Time plus 30 mins: " + plusMins);
Here are the results.
Current Time: 12:43:58.048247
Local Date Time object: 2021-11-12T12:43:58.048247
Comparing times: 1Hour: 12
Is local time after pastTime? true
Time minus 5 hours: 07:43:58.048247
Time plus 30 mins: 13:13:58.048247
The main is:
public static void main(String[] args){
currentTime();
}
Chapter 4 Numbers aNd dates


125

Download 3.2 Mb.

Do'stlaringiz bilan baham:
1   ...   71   72   73   74   75   76   77   78   ...   245




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