zl程序教程

您现在的位置是:首页 >  后端

当前栏目

【说站】java时间日期API的整理

JAVA日期API 时间 整理
2023-06-13 09:13:23 时间

java时间日期API的整理

1、Clock提供了访问当前时间和日期的功能。Clock对当前时区敏感,可以用来代替System.currenttimeMillis()获得当前毫秒时间。

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

2、本地时间类表示没有指定时区的时间。

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、时区类可以用ZoneId表示。时区类的对象可以通过静态工厂方法轻松获得。

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]

以上就是java时间日期API的整理,我们可以对其中的一些时间问题进行练习,在java新版本中时间API的相较以往有所不同,感兴趣的话都尝试一下吧。