加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 考虑到夏令时,将本地时间转换为UTC时间,反之亦然

发布时间:2020-12-14 05:33:29 所属栏目:Java 来源:网络整理
导读:我知道如何将本地时间转换为UTC时间,反之亦然. 但是,在这样做时,我对夏令时间(DST)的处理感到非常困惑. 任何人都可以回答以下问题: 1.在时区之间转换时,java内部是否处理DST? 2.在时区之间转换时需要做些什么? 任何有关这个更清楚的解释的好文章? 提前致
我知道如何将本地时间转换为UTC时间,反之亦然.
但是,在这样做时,我对夏令时间(DST)的处理感到非常困惑.

任何人都可以回答以下问题:
1.在时区之间转换时,java内部是否处理DST?
2.在时区之间转换时需要做些什么?
任何有关这个更清楚的解释的好文章?

提前致谢.

解决方法

你确定你知道如何将日期转换为UTC并返回?正确?
恐怕我怀疑.

>是的.
>你不需要转换,你只需要分配正确的TimeZone.
>你需要一篇文章?好的,我正在做这件事,但现在让我在这里给出答案.

第一件事先.您的程序应该在UTC TimeZone内部存储Date(或Calendar).那么事实上在GMT,因为Java没有闰秒,但这是另一个故事.
当你需要“转换”的唯一的地方是当你要给用户显示时间.这也是发送电子邮件.在这两种情况下,您需要格式化日期以获取其文本表示.为此,您将使用DateFormat并分配正确的TimeZone:

// that's for desktop application
    // for web application one needs to detect Locale
    Locale locale = Locale.getDefault();
    // again,this one works for desktop application
    // for web application it is more complicated
    TimeZone currentTimeZone = TimeZone.getDefault();
    // in fact I could skip this line and get just DateTime instance,// but I wanted to show how to do that correctly for
    // any time zone and locale
    DateFormat formatter = DateFormat.getDateTimeInstance(
            DateFormat.DEFAULT,DateFormat.DEFAULT,locale);
    formatter.setTimeZone(currentTimeZone);

    // Dates "conversion"
    Date currentDate = new Date();
    long sixMonths = 180L * 24 * 3600 * 1000;
    Date inSixMonths = new Date(currentDate.getTime() + sixMonths);

    System.out.println(formatter.format(currentDate));
    System.out.println(formatter.format(inSixMonths));
    // for me it prints
    // 2011-05-14 16:11:29
    // 2011-11-10 15:11:29

    // now for "UTC"
    formatter.setTimeZone(TimeZone.getTimeZone("UTC"));
    System.out.println(formatter.format(currentDate));
    System.out.println(formatter.format(inSixMonths));
    // 2011-05-14 14:13:50
    // 2011-11-10 14:13:50

可以看到,Java关心处理DST.您当然可以手动处理,只需阅读TimeZone related JavaDoc.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读