美文网首页Joda time
Joda-Time TimeZone 时区

Joda-Time TimeZone 时区

作者: ba2cb747365a | 来源:发表于2018-11-25 15:21 被阅读102次

    背景

    故事5已经提到了,统一的全球系统时钟在不同的时区时间是不一样的。当北京,伦敦,东京的程序员同时写下new Date()的时候,他们打印出来的时间是不一样的。

    补充

    System.currentTimeMillis() 返回当前的计算机时间,请记住这个毫秒值在世界所有的机器上生成都是一样的。

    核心对象

    DateTimeZone
    Joda-Time中的时区

    示例

    1. 获取伦敦时区


      image.png
    2. 获取UTC时间


      image.png
    3. 通过偏移的小时来获取时区


      image.png
    4. 获取当前伦敦本地时间


      image.png
    • 可以看到伦敦时间比北京时间晚了八个小时
    1. 获取伦敦与北京当前相同的时间


      image.png
    2. 相同的毫秒值在不同的时区下拥有不同的时间
    // Java:
    long t = System.currentTimeMillis();
    System.out.println("long = " + t);
    
    // current time zone:
    SimpleDateFormat sdf_default = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    System.out.println(sdf_default.format(t));
    
    // +8:00 time zone:
    SimpleDateFormat sdf_8 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    sdf_8.setTimeZone(TimeZone.getTimeZone("GMT+8:00"));
    System.out.println("GMT+8:00 = " + sdf_8.format(t));
    
    // +7:00 time zone:
    SimpleDateFormat sdf_7 = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    sdf_7.setTimeZone(TimeZone.getTimeZone("GMT+7:00"));
    System.out.println("GMT+7:00 = " + sdf_7.format(t));
    
    // -9:00 time zone:
    SimpleDateFormat sdf_la = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    sdf_la.setTimeZone(TimeZone.getTimeZone("America/Los_Angeles"));
    System.out.println("America/Los_Angeles = " + sdf_la.format(t));
    

    总结

    • 世界各地服务器生成的毫秒值是一样的
    • 在不同的时区,相同的毫秒值对应的时间是不一样的,比如北京比伦敦早8个小时
    • new Date() 默认取的是系统时区,如果将new Date() 存入数据库,当应用服务器的时区改变或者数据库的时区改变后,就会出现时间上的错误。

    相关文章

      网友评论

        本文标题:Joda-Time TimeZone 时区

        本文链接:https://www.haomeiwen.com/subject/xgspqqtx.html