java – 考虑到夏令时,将本地时间转换为UTC时间,反之亦然
发布时间:2020-12-14 05:33:29 所属栏目:Java 来源:网络整理
导读:我知道如何将本地时间转换为UTC时间,反之亦然. 但是,在这样做时,我对夏令时间(DST)的处理感到非常困惑. 任何人都可以回答以下问题: 1.在时区之间转换时,java内部是否处理DST? 2.在时区之间转换时需要做些什么? 任何有关这个更清楚的解释的好文章? 提前致
我知道如何将本地时间转换为UTC时间,反之亦然.
但是,在这样做时,我对夏令时间(DST)的处理感到非常困惑. 任何人都可以回答以下问题: 提前致谢. 解决方法
你确定你知道如何将日期转换为UTC并返回?正确?
恐怕我怀疑. >是的. 第一件事先.您的程序应该在UTC TimeZone内部存储Date(或Calendar).那么事实上在GMT,因为Java没有闰秒,但这是另一个故事. // 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. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |