Вопрос

I am receiving a java.sql.Timestamp in UTC for example:

2014-04-03 08:25:20.0

I know, that this timestamp is in UTC. And I know that the target timezone for this timestamp. Example:

Europe/Berlin

Now I 'd like to convert the UTC timestmap to a localized timestamp. With the correct daylight savings, of course.

My attempt so far:

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)

This prints:

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

Shouldn't the correct localized timestamp be:

2014-04-03T10:25:20.000+02:00
Это было полезно?

Решение

I think that this might work

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)

Другие советы

The other answer seems needlessly complicated. Here is my take using Joda-Time 2.3.

Berlin is 2 hours ahead of UTC because of Daylight Saving Time nonsense. So if UTC is 8 AM, then Berlin is 10 AM.

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 );

Dump to console…

System.out.println( "input: " + input );
System.out.println( "dateTimeUtc: " + dateTimeUtc );
System.out.println( "dateTimeBerlin: " + dateTimeBerlin );

When run…

input: 2014-04-03T08:25:20.0
dateTimeUtc: 2014-04-03T08:25:20.000Z
dateTimeBerlin: 2014-04-03T10:25:20.000+02:00
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top