Java转换UTC/CET时间

标签 java timezone

我想将给定的日期时间(它是 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/

相关文章:

java - 如何修复由 : java. lang.ClassCastException : androidx. appcompat.widget.AppCompatTextView 无法转换为 android.widget.Button 引起的问题

java - Java中的链表FIFO队列集合

node.js - Node.js 从哪里获取时区数据?

centos - php 5.6.x 及更高版本中的时区不完全是?

javascript - 如何使用 Moment.js 获取 EST 的今天开始时间和当前时间

java - Spring MVC;测试重定向是否是相对的

Java 7 update 25 不允许在安装安全管理器的情况下进行类加载?

java - 如何使用捕捉到道路在道路 api 中请求?

ruby-on-rails - 在 Rails 或一般的 Ruby 中,我如何知道日期时间字符串是否对应于具有 DST 或不具有 DST 的日期时间?

r - 如何在 POSIXct 中开始一天