Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/330.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 将UTC时间戳转换为任意时区_Java_Datetime_Jodatime - Fatal编程技术网

Java 将UTC时间戳转换为任意时区

Java 将UTC时间戳转换为任意时区,java,datetime,jodatime,Java,Datetime,Jodatime,我收到一个UTC格式的java.sql.Timestamp,例如: 2014-04-03 08:25:20.0 我知道,这个时间戳是UTC的。我知道这个时间戳的目标时区。例如: 欧洲/柏林 现在,我想将UTC时间映射转换为本地化的时间戳。当然,用正确的夏令时 我迄今为止的努力: println(msg.timestamp) println(new DateTime(msg.timestamp)) val storeTz = DateTimeZone.forID(store.timezone) p

我收到一个UTC格式的java.sql.Timestamp,例如:

2014-04-03 08:25:20.0

我知道,这个时间戳是UTC的。我知道这个时间戳的目标时区。例如:

欧洲/柏林

现在,我想将UTC时间映射转换为本地化的时间戳。当然,用正确的夏令时

我迄今为止的努力:

println(msg.timestamp)
println(new DateTime(msg.timestamp))
val storeTz = DateTimeZone.forID(store.timezone)
println(new DateTime(msg.timestamp, storeTz))
val localTimestamp = new DateTime(msg.timestamp).withZone(storeTz)
println(localTimestamp)
这张照片是:

2014-04-03 08:25:20.0
2014-04-03T08:25:20.000+02:00
2014-04-03T07:25:20.000+01:00
2014-04-03T07:25:20.000+01:00
正确的本地化时间戳不应该是:

2014-04-03T10:25:20.000+02:00

我想这可能行得通

println(msg.timestamp)
println(new DateTime(msg.timestamp))
val storeTz = DateTimeZone.forID(store.timezone)
println(new DateTime(msg.timestamp, storeTz))
val localTimestamp = new DateTime(msg.timestamp).withZoneRetainFields(DateTimeZone.UTC).toDateTime(storeTz)
println(localTimestamp)

另一个答案似乎不必要地复杂。这是我用Joda Time 2.3拍摄的照片

柏林比UTC早2个小时,因为夏令时毫无意义。所以如果UTC是上午8点,那么柏林是上午10点

String inputRaw = "2014-04-03 08:25:20.0";
String input = inputRaw.replace( " ", "T" ); // Convert to strict ISO 8601 format.

DateTime dateTimeUtc = new DateTime( input, DateTimeZone.UTC );

DateTimeZone timeZoneBerlin = DateTimeZone.forID( "Europe/Berlin" );
DateTime dateTimeBerlin = dateTimeUtc.withZone( timeZoneBerlin );
转储到控制台

System.out.println( "input: " + input );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeBerlin: " + dateTimeBerlin );
当运行时

输入:2014-04-03T08:25:20.0
日期时间UTC:2014-04-03T08:25:20.000Z
柏林时间:2014-04-03T10:25:20.000+02:00

上面写的是+02:00落后。我想10:00+02:00应该是12:00。(注意+02:00附近缺少的()。所以08:00+02:00可能已经是您想要的输出,只是格式错误。这几乎是正确的。现在我得到了本地化的时间戳,但似乎现在考虑到了当前的夏令时。输出为2014-04-03T09:25:20.000+02:00根据图纸,这是正确的。欧洲/柏林的时间与UTC相差2小时,是吗?但是完全本地化的时间戳应该是2014-04-03T10:25:20.000+02:00,不是吗?我现在看到问题了,你必须说时间戳在UTC时区,但保留字段值。然后转换到正确的时区。请参见编辑。请参见