转自: Java的日期与时间之java.time.ZonedDateTime简介说明 下文笔者讲述java.time.ZonedDateTime的简介说明,如下所示
ZonedDateTime简介说明
ZonedDateTime类
是Java 8中日期时间功能里
用于表示带时区的日期与时间信息的类
可以用于表示一个真实事件的开始时间
如:某火箭升空时间等
ZonedDateTime类的值是不可变的
其计算方法会返回一个新的ZonedDateTime实例
创建一个ZonedDateTime实例
创建ZonedDateTime实例有好几种方式: 方式1:使用当前时间作为值新建对象: ZonedDateTime dateTime = ZonedDateTime.now(); 方式2:使用指定的年月日、时分秒、纳秒以及时区ID来新建ZonedDateTime对象 ZoneId zoneId = ZoneId.of("UTC+1"); ZonedDateTime dateTime2 = ZonedDateTime.of(2022, 08, 14, 21, 49, 30, 1234, zoneId);
访问ZonedDateTime对象的时间
可通过这些方法访问其日期时间信息:
getYear() getMonth() getDayOfMonth() getDayOfWeek() getDayOfYear() getHour() getMinute() getSecond() getNano() 以上方法,将返回int值
ZonedDateTime涉及的计算方法
ZonedDateTime类包含很多方法,如下所示:
plusYears() plusMonths() plusDays() plusHours() plusMinutes() plusSeconds() plusNanos() minusYears() minusMonths() minusDays() minusHours() minusMinutes() minusSeconds() minusNanos()
例:
ZonedDateTime zoneDateTime = previousDateTime.plus(Period.ofDays(3));
时区
java中时区: 使用ZoneId类表示 可使用ZoneId.now()或ZoneId.of(“xxx”) 进行实例化: ZoneId zoneId = ZoneId.of("UTC+2"); ZoneId zoneId3 = ZoneId.of("Asia/Shanghai"); of方法接收的参数是:时区ID 如:UTC+2 是距离UTC时间2小时的时间 也可以使用时区名字