我想将给定的日期时间(它是 utc 日期时间)转换为 CET 中相应的日期时间,并正确映射欧洲夏令时/冬令时(夏令时)。我设法使用 java.time
相反(CET 到 UTC) :
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 cetTimeZoned = ZonedDateTime.of(timeInUtc,ZoneId.of("UTC"));
return cetTimeZoned.withZoneSameInstant(ZoneOffset.of(???)).toLocalDateTime(); // what to put here?
}
我怎样才能做到这一点?
最佳答案
只需使用 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();
}
}
关于Java转换UTC/CET时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43042763/