ZonedDateTime 类声明
public final class ZonedDateTime extends Object implements Temporal, ChronoZonedDateTime<LocalDate>, Serializable { //class body }
Java 8 中引入的 java.time.ZonedDateTime 类表示 ISO-8601 日历系统中带有时区信息的日期和时间。
此类存储所有日期和时间字段,精度为纳秒。
ZonedDateTime
持有相当于三个独立对象的状态,一个 LocalDateTime
,一个 ZoneId
和解析的 ZoneOffset
。
请注意,ZonedDateTime
实例是不可变的和线程安全的。
Java 如何将 ZonedDateTime 格式化为字符串
使用 ZonedDateTime.format(DateTimeFormatter)
方法将本地时间格式化为所需的字符串表示形式。
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss a"); ZonedDateTime now = ZonedDateTime.now(); String dateTimeString = now.format(formatter); //2019-03-28 14:47:33 PM
Java 如何创建 ZonedDateTime
通常,我们会在两种情况下创建 ZonedDateTime
实例,例如:获取带有区域信息的当前时间戳或者创建表示特定时区中的时间戳。
获取当前 ZonedDateTime
使用以下工厂方法获取当前时间戳。
ZonedDateTime now = ZonedDateTime.now(); ZonedDateTime now = ZonedDateTime.now( ZoneId.of("GMT+05:30") ); //Time in IST
创建指定的 ZonedDateTime
要创建具有特定日期、时间和区域信息的时间戳,请使用以下方法。
//1 - All date parts are inplace ZoneId zoneId = ZoneId.of("UTC+1"); ZonedDateTime zonedDateTime1 = ZonedDateTime.of(2015, 11, 30, 23, 45, 59, 1234, zoneId); //========= //2 - Using existing local date and time values LocalDate localDate = LocalDate.of(2019, 03, 12); LocalTime localTime = LocalTime.of(12, 44); ZoneId zoneId = ZoneId.of("GMT+05:30"); ZonedDateTime timeStamp = ZonedDateTime.of( localDate, localTime, zoneId );
on
it
road
.com
Java 如何将字符串解析为 ZonedDateTime
ZonedDateTime
类有两个重载的 parse() 方法来将字符串中的时间转换为本地时间实例。
parse(CharSequence text) //1 parse(CharSequence text, DateTimeFormatter formatter) //2
- 如果字符串包含
ISO_ZONED_DATE_TIME
模式中的时间,则使用第一种方法,例如:2019-03-28T10:15:30+01:00[Europe/Paris]。这是默认模式。 - 对于任何其他日期时间模式,我们需要使用第二种方法,我们将日期时间作为字符串以及表示该日期时间字符串模式的格式化程序进行传递。
//1 - default pattern String timeStamp = "2019-03-27T10:15:30"; ZonedDateTime localTimeObj = ZonedDateTime.parse(time); //2 - specified pattern DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss a"); String timeStamp1 = "2019-03-27 10:15:30 AM"; ZonedDateTime localTimeObj1 = ZonedDateTime.parse(timeStamp1, formatter);
如何修改ZonedDateTime
ZonedDateTime
提供了以下修改方法。
所有方法都返回一个新的 ZonedDateTime
实例,因为现有的实例总是不可变的。
plusYears()
plusMonths()
plusDays()
plusHours()
plusMinutes()
plusSeconds()
plusNanos()
minusYears()
minusMonths()
minusDays()
minusHours()
minusMinutes()
minusSeconds()
minusNanos()
ZonedDateTime now = ZonedDateTime.now(); //3 hours later ZonedDateTime zonedDateTime1 = now.plusHours(3); //3 minutes earliar ZonedDateTime zonedDateTime2 = now.minusMinutes(3); //Next year same time ZonedDateTime zonedDateTime2 = now.plusYears(1); //Last year same time ZonedDateTime zonedDateTime2 = now.minusYears(1);
日期:2020-09-17 00:09:39 来源:oir作者:oir