java JodaTime :将本地转换为 UTC 歧义
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16809802/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
JodaTime : Convert local to UTC ambiguity
提问by Parvin Gasimzade
I am trying to convert local date to UTC by using Joda Time. The code that I used is shown below and it works great.
我正在尝试使用Joda Time将本地日期转换为 UTC 。我使用的代码如下所示,效果很好。
Date localDate = new Date();
System.out.println("Local Date : " + localDate);
DateTimeZone tz = DateTimeZone.getDefault();
Date utcDate = new Date(tz.convertLocalToUTC(localDate.getTime(), false));
System.out.println("UTC Date : " + utcDate);
Output :
Local Date : Wed May 29 11:54:46 EEST 2013
UTC Date : Wed May 29 08:54:46 EEST 2013
But, if I send UTC Date as a parameter to the DateTimeZone.convertLocalToUTC()method, it also decreases the hour by 3. However, since it is UTC Date, I expect it not to convert date again. Is this a bug or am I missing something?
但是,如果我将 UTC 日期作为参数发送到DateTimeZone.convertLocalToUTC()方法,它也会将小时数减少 3。但是,由于它是 UTC 日期,我希望它不会再次转换日期。这是一个错误还是我错过了什么?
Date localDate = new Date();
System.out.println("Local Date : " + localDate);
DateTimeZone tz = DateTimeZone.getDefault();
Date utcDate = new Date(tz.convertLocalToUTC(localDate.getTime(), false));
System.out.println("UTC Date : " + utcDate);
Date utcDate2 = new Date(tz.convertLocalToUTC(utcDate.getTime(), false));
System.out.println("UTC Date 2 : " + utcDate2);
Output :
Local Date : Wed May 29 11:54:46 EEST 2013
UTC Date : Wed May 29 08:54:46 EEST 2013
UTC Date 2 : Wed May 29 05:54:46 EEST 2013
回答by harsh
As per javadoc of convertLocalToUTC
根据 javadoc convertLocalToUTC
Converts a local instant to a standard UTC instant with the same local time. This conversion is used after performing a calculation where the calculation was done using a simple local zone.
将本地时刻转换为具有相同本地时间的标准 UTC 时刻。在执行计算后使用此转换,其中计算是使用简单的本地区域完成的。
Methods makes no assumption or validation that passed date is in UTC
or not, it always consider passed date as local and converts to UTC
. Your program output is correct.
方法不假设或验证传递的日期是否在UTC
,它总是将传递的日期视为本地并转换为UTC
. 你的程序输出是正确的。
回答by rgeorge
Look at it from the convertLocalToUTC()
methods point of view. It just takes a long
and a boolean
. It does not have any knowledge that the long you are passing it is UTC
or not. It assumes that you are passing a long
that is local time and adjusts it accordingly.
从convertLocalToUTC()
方法的角度来看。它只需要一个long
和一个boolean
。它不知道您通过它的时间长短UTC
。它假设您传递的long
是当地时间并相应地调整它。