简体   繁体   English

如何在java中将UTC时间转换为CET时间

[英]How to convert a UTC time to CET time in java

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. 如果我使用它,我会在我放入的同时出去。

I strongly advise you to avoid the use of timezone names like "CET" because of the inherent localized nature. 我强烈建议您避免使用像“CET”这样的时区名称,因为它具有固有的本地化特性。 This might only be okay in formatted output for the end user, but not in internal coding. 这可能仅适用于最终用户的格式化输出,但不适用于内部编码。

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/BerlinEurope/Paris等。在我的时区“Europe / Berlin”中,您的代码如下所示:

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 conversion and will therefore not change anything if your CET zone is internally recognized with equal timezone offset compared with your system timezone. 请记住,表达式new LocalDateTime(utdDate.getTime()) 隐式使用系统时区进行转换 ,因此如果您的CET区域在内部被识别时与系统时区相比具有相等的时区偏移,则不会更改任何内容。 In order to force JodaTime to recognize an UTC-input you should specify it like this way: 为了强制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. 此示例保留了自UNIX纪元以来的绝对时间(以毫秒为单位)。 If you want to preserve the fields and thereby changing the instant then you can use the method withZoneRetainFields : 如果要保留字段并因此更改瞬间,则可以使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM