如何在java中将UTC时间转换为CET时间
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23112489/
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
How to convert a UTC time to CET time in java
提问by simonC
How can I convert a UTC time to CET time possibly using yoda time library in Java?
如何使用 Java 中的 yoda 时间库将 UTC 时间转换为 CET 时间?
I was triing wit this but it looks like I'm doing something wrong
我正在尝试机智,但看起来我做错了什么
DateTime dateTime = new LocalDateTime(utdDate.getTime()).toDateTime(DateTimeZone.forID("CET"));
if I use this I get out the same time as I put in.
如果我使用它,我会在放入的同时退出。
采纳答案by Meno Hochschild
I strongly advise you to avoid the use of timezone names like "CET" because of the inherent localized nature. This might only be okay in formatted output for the end user, but not in internal coding.
由于固有的本地化性质,我强烈建议您避免使用“CET”等时区名称。这可能只适用于最终用户的格式化输出,但不适用于内部编码。
CET stands for many different timezone ids like the IANA-IDs Europe/Berlin
, Europe/Paris
etc. In my timezone "Europe/Berlin" your code works like followed:
CET代表许多不同的时区的ID,如IANA-ID的Europe/Berlin
,Europe/Paris
等等。在我的时区“欧洲/柏林”你的代码就像如下:
DateTime dateTime =
new LocalDateTime(utdDate.getTime()) // attention: implicit timezone conversion
.toDateTime(DateTimeZone.forID("CET"));
System.out.println(dateTime.getZone()); // CET
System.out.println(dateTime); // 2014-04-16T18:39:06.976+02:00
Remember that the expression new LocalDateTime(utdDate.getTime())
implicitly uses the system timezone for conversionand will therefore not change anything if your CET zone is internally recognized with equal timezone offset compared with your system timezone. In order to force JodaTime to recognize an UTC-input you should specify it like this way:
请记住,该表达式new LocalDateTime(utdDate.getTime())
隐式使用系统时区进行转换,因此如果您的 CET 区域在内部被识别为与系统时区相比具有相同的时区偏移量,则不会更改任何内容。为了强制 JodaTime 识别 UTC 输入,您应该像这样指定它:
Date utdDate = new Date();
DateTime dateTime = new DateTime(utdDate, DateTimeZone.UTC);
System.out.println(dateTime); // 2014-04-16T16:51:31.195Z
dateTime = dateTime.withZone(DateTimeZone.forID("Europe/Berlin"));
System.out.println(dateTime); // 2014-04-16T18:51:31.195+02:00
This example preserves the instant that is the absolute time in milliseconds since UNIX epoch. If you want to preserve the fields and thereby changing the instant then you can use the method withZoneRetainFields
:
此示例保留了自 UNIX 纪元以来的绝对时间(以毫秒为单位)的时刻。如果您想保留字段并从而更改瞬间,则可以使用以下方法withZoneRetainFields
:
Date utdDate = new Date();
dateTime = new DateTime(utdDate, DateTimeZone.UTC);
System.out.println(dateTime); // 2014-04-16T16:49:08.394Z
dateTime = dateTime.withZoneRetainFields(DateTimeZone.forID("Europe/Berlin"));
System.out.println(dateTime); // 2014-04-16T16:49:08.394+02:00