Question

How can I convert a UTC time to CET time possibly using yoda time library in Java?

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.

Was it helpful?

Solution

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 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:

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. In order to force JodaTime to recognize an UTC-input you should specify it like this way:

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:

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top