6

I want to convert a given date time (which is a utc date time) to the corresponding date time in CET with a proper mapping of the european summer/winter time switch (daylight saving time). I managed to to the opposite (CET to UTC) using java.time:

public static LocalDateTime cetToUtc(LocalDateTime timeInCet) {
    ZonedDateTime cetTimeZoned = ZonedDateTime.of(timeInCet, ZoneId.of("CET"));
    return cetTimeZoned.withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
}

But I fail to go the opposite way:

public static LocalDateTime utcToCet(LocalDateTime timeInUtc) {
     ZonedDateTime cetTimeZoned = ZonedDateTime.of(timeInUtc,ZoneId.of("UTC"));
     return cetTimeZoned.withZoneSameInstant(ZoneOffset.of(???)).toLocalDateTime(); // what to put here?
 }

How can I do that?

2
  • 3
    why not use ZoneId.of("CET")?
    – Viet
    Commented Mar 27, 2017 at 9:51
  • @Jerry06 Ok thanks, this works. I did not really realized that I can also use a Zone instead of an ZoneOffset Commented Mar 27, 2017 at 9:58

2 Answers 2

8

Just use ZoneId.of("CET")

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;

public class Main {

    public static void main(String args[])
    {
        LocalDateTime date = LocalDateTime.now(ZoneId.of("CET"));
        System.out.println(date);

        LocalDateTime utcdate = cetToUtc(date);
        System.out.println(utcdate);

        LocalDateTime cetdate = utcToCet(utcdate);
        System.out.println(cetdate);
    }

    public static LocalDateTime cetToUtc(LocalDateTime timeInCet) {
        ZonedDateTime cetTimeZoned = ZonedDateTime.of(timeInCet, ZoneId.of("CET"));
        return cetTimeZoned.withZoneSameInstant(ZoneOffset.UTC).toLocalDateTime();
    }

    public static LocalDateTime utcToCet(LocalDateTime timeInUtc) {
         ZonedDateTime utcTimeZoned = ZonedDateTime.of(timeInUtc,ZoneId.of("UTC"));
         return utcTimeZoned.withZoneSameInstant(ZoneId.of("CET")).toLocalDateTime();
     }
}
4

TL;DR: In both of your methods use ZoneId.of("Europe/Rome") (or your favourite city in the CET time zone) and ZoneOffset.UTC.

As Jerry06 said in a comment, using ZoneId.of("CET") again works (you already used it in your first method).

However, the three-letter time zone abbreviations are not recommended, and many of them are ambiguous. They recommend you use one of the city time zone IDs instead, for example ZoneId.of("Europe/Rome") for CET (this will give you CEST starting yesterday). Also rather than ZoneId.of("UTC") they recommend ZoneOffset.UTC. Passing a ZoneOffset works because ZoneOffset is one of the subclasses of ZoneId.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.