Home  >  Article  >  Java  >  How to use java time and date API

How to use java time and date API

王林
王林forward
2023-05-03 08:10:141256browse

1. Clock provides the function of accessing the current time and date. Clock is sensitive to the current time zone and can be used instead of System.currenttimeMillis() to obtain the current millisecond time.

Clock clock = Clock.systemDefaultZone();
long millis = clock.millis();
 
Instant instant = clock.instant();
Date legacyDate = Date.from(instant);   // legacy java.util.Date

2. The local time class represents the time without a specified time zone.

LocalTime now1 = LocalTime.now(zone1);
LocalTime now2 = LocalTime.now(zone2);
 
System.out.println(now1.isBefore(now2));  // false
 
long hoursBetween = ChronoUnit.HOURS.between(now1, now2);
long minutesBetween = ChronoUnit.MINUTES.between(now1, now2);
 
System.out.println(hoursBetween);       // -3
System.out.println(minutesBetween);     // -239

3. The time zone class can be represented by ZoneId. Objects of the time zone class can be easily obtained through static factory methods.

System.out.println(ZoneId.getAvailableZoneIds());
// prints all available timezone ids
 
ZoneId zone1 = ZoneId.of("Europe/Berlin");
ZoneId zone2 = ZoneId.of("Brazil/East");
System.out.println(zone1.getRules());
System.out.println(zone2.getRules());
 
// ZoneRules[currentStandardOffset=+01:00]
// ZoneRules[currentStandardOffset=-03:00]

The above is the detailed content of How to use java time and date API. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete