[英]How to convert a UTC time to CET time in java
如何使用Java中的yoda时间库将UTC时间转换为CET时间?
我正在嘲笑这个,但看起来我做错了什么
DateTime dateTime = new LocalDateTime(utdDate.getTime()).toDateTime(DateTimeZone.forID("CET"));
如果我使用它,我会在我放入的同时出去。
我强烈建议您避免使用像“CET”这样的时区名称,因为它具有固有的本地化特性。 这可能仅适用于最终用户的格式化输出,但不适用于内部编码。
CET代表许多不同的时区ID,如IANA-ID Europe/Berlin
, Europe/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
请记住,表达式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
此示例保留了自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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.