`
somefuture
  • 浏览: 1093929 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

java8中的时间处理7 - 向前兼容(新老类转换)

 
阅读更多

我们不太可能使用jdk8以后就把原来的代码都改成新api。所以新旧日期类会共存一段时间。

这篇提供他们之间的转换。

    public static void main(String[] args) {
        //Date 转 Instant
        Instant timestamp = new Date().toInstant();
        //其他类都有ofInstant方法用来转换Instant
        LocalDateTime date = LocalDateTime.ofInstant(timestamp, ZoneId.of(ZoneId.SHORT_IDS.get("CTT")));
        System.out.println(date);

        //Calendar 转 Instant
        Instant time = Calendar.getInstance().toInstant();
        System.out.println(time);
        //TimeZone 转 ZoneId
        ZoneId defaultZone = TimeZone.getDefault().toZoneId();
        System.out.println(defaultZone);

        //Calendar 转 ZonedDateTime
        ZonedDateTime gregorianCalendarDateTime = new GregorianCalendar().toZonedDateTime();
        System.out.println(gregorianCalendarDateTime);

        //兼容API
        Date dt = Date.from(Instant.now());
        System.out.println(dt);

        TimeZone tz = TimeZone.getTimeZone(defaultZone);
        System.out.println(tz);

        GregorianCalendar gc = GregorianCalendar.from(gregorianCalendarDateTime);
        System.out.println(gc);
    }

 

 

分享到:
评论

相关推荐

    bootstrap--excel表上传所需jar包.zip

    Bootstrap Excel表上传是一个常见的功能需求,特别是在Web应用中处理数据导入和导出。在这个场景下,`bootstrap-fileinput`是一个非常流行的前端插件,它扩展了Bootstrap的输入元素,提供了美观且功能丰富的文件上传...

    protobuf-3.2.0rc2

    5. **版本兼容性**:protobuf支持向前和向后兼容,即使数据结构有所修改,老版本的代码通常也能读取新版本序列化的数据。 在protobuf-3.2.0rc2这个版本中,可能包含以下改进和特性: - 性能优化:相对于之前的版本...

    protoc.exe-3.9.1-win64.rar

    5. **版本兼容性**:protobuf设计有良好的向前和向后兼容性,升级protobuf版本时,老版本的序列化数据仍可被新版本解析。 使用protobuf的优点: 1. **效率**:protobuf的二进制编码比文本格式(如JSON)更紧凑,...

    ProtocolBuffer

    4. **版本兼容性**:Protocol Buffer设计时考虑了向前和向后兼容性,即使新版本的消息结构有所改变,旧版本的代码也能正确处理。 **VS2008和VS2017兼容性**: 这个压缩包可能包含了为不同Visual Studio版本编译的...

    开源项目-google-protobuf.zip

    3. **易于扩展**:可以通过增加、修改 .proto 文件中的字段来扩展数据结构,而不会破坏向前兼容性。 4. **版本控制**:新旧版本的协议可以并存,且老版本的代码仍能读取新版本的数据。 在实际应用中,Protobuf 常...

    protobuf2.5.0

    6. **版本兼容性**:protobuf设计时考虑了向前和向后的兼容性,意味着在不更改现有字段ID的情况下添加新字段,老版本的代码仍能正确解析新版本的序列化数据。 7. **.proto文件的语法**:包括基本数据类型(如int32...

Global site tag (gtag.js) - Google Analytics