Raphael Roth
Raphael Roth

Reputation: 27373

Java convert UTC / CET time

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?

Upvotes: 6

Views: 32084

Answers (2)

Anonymous
Anonymous

Reputation: 86120

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.

Upvotes: 4

amchacon
amchacon

Reputation: 1961

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

Upvotes: 8

Related Questions