Java.time.ZonedDateTime带时区的日期与时间信息的类

 duang,最近搭建了一个自己的博客小破站,欢迎各位小伙伴来访:Ares的小破站 (ares-stack.cn)

ZonedDateTime类是Java 8中日期时间功能里,用于表示带时区的日期与时间信息的类。可以用于表示一个真实事件的开始时间,如某火箭升空时间等等。 
ZonedDateTime 类的值是不可变的,所以其计算方法会返回一个新的ZonedDateTime 实例。

1,创建一个ZonedDateTime实例 
有多种方式可以新建ZonedDateTime实例。比如使用当前时间作为值新建对象: 

ZonedDateTime dateTime = ZonedDateTime.now(); 

另一种方式是使用指定的年月日、时分秒、纳秒以及时区ID来新建对象:

ZoneId zoneId = ZoneId.of("UTC+1");
ZonedDateTime dateTime2 = ZonedDateTime.of(2015, 11, 30, 23, 45, 59, 1234, zoneId);

2,访问ZonedDateTime对象的时间 
你可以通过这些方法访问其日期时间:

getYear()
getMonth()
getDayOfMonth()
getDayOfWeek()
getDayOfYear()
getHour()
getMinute()
getSecond()
getNano()

这些方法中有一些返回int有一些返回枚举类型,但可以通过枚举类型中的getValue()方法来获得int值。

3,返回具有不同时区的此日期时间的副本,保留当前时间。

// 传入参数zonedDateTime,或其他时区时间
// 调用withZoneSameInstant方法,转换为:系统默认时区
zonedDateTime = zonedDateTime.withZoneSameInstant(ZoneId.systemDefault());

返回具有不同时区的此日期时间的副本,保留当前时间: 

    /**
     * Returns a copy of this date-time with a different time-zone,
     * retaining the instant.
     */
    @Override
    public ZonedDateTime withZoneSameInstant(ZoneId zone) {
        Objects.requireNonNull(zone, "zone");
        return this.zone.equals(zone) ? this :
            create(dateTime.toEpochSecond(offset), dateTime.getNano(), zone);
    }

获取系统默认时区: 

    /**
     * Gets the system default time-zone.
     */
    public static ZoneId systemDefault() {
        return TimeZone.getDefault().toZoneId();
    }

DateTimeFormatter

DateTimeFormatter类是Java 8中日期时间功能里,用于解析和格式化日期时间的类,位于java.time.format包下。

预定义的DateTimeFormatter实例 
DateTimeFormatter类包含一系列预定义(常量)的实例,可以解析和格式化一些标准时间格式。这将让你免除麻烦的时间格式定义,类中包含如下预定义的实例:

BASIC_ISO_DATE

ISO_LOCAL_DATE
ISO_LOCAL_TIME
ISO_LOCAL_DATE_TIME
...

每个预定义的DateTimeFormatter实例都有不同的日期格式,我就不解释全部的了。具体的可以查阅Java官方文档,但我在这篇的后续中会解释其中几个,以方便理解。

格式化日期 
当你获取一个DateTimeFormatter实例后,就可以用format()方便来将一个日期格式化为某种字符串,例如:

DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE;
String formattedDate = formatter.format(LocalDate.now());
System.out.println(formattedDate);

这个样例把LocalDate对象格式化了,并输出20150703,这个输出表示现在2015年,7月3日。 
再举一个关于ZonedDateTime的例子:

DateTimeFormatter formatter = DateTimeFormatter.BASIC_ISO_DATE;
String formattedZonedDate = formatter.format(ZonedDateTime.now());
System.out.println("formattedZonedDate = " + formattedZonedDate);

这个例子会输出:20150703+0200 
表示今年2015年,7月3日,位于UTC+2时区。

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("HH:mm");
String formattedDate = formatter.format(LocalDate.now());
System.out.println(formattedDate);


参考来源于:

Java的日期与时间(十五)java.time.ZonedDateTime_ArnoldTang的博客-CSDN博客_zoneddatetime计算离明天多长

Java的日期与时间(十六)java.time.format.DateTimeFormatter_ArnoldTang的博客-CSDN博客_time.format() datetimeformatter

  • 2
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值