【问题标题】:how to convert from UTC to CEST timezone in java [duplicate]如何在java中从UTC转换为CEST时区[重复]
【发布时间】:2016-09-16 08:09:46
【问题描述】:

我想从 UTC 时区 (ex.2016-05-19T06:10:00) 转换为 CEST 时区 (2016-05-19T08:10:00) 到 java 中的字符串。

【问题讨论】:

  • 堆栈溢出有很多类似的问题。提问前请先搜索。谢谢。
  • 我已经浏览过它们但没有用。
  • 什么意思?这些问题展示了如何在两个时区之间进行转换,只需设置您想要的区域。

标签: java oop


【解决方案1】:

java.time 解决方案:

public static void main(String[] args) {
    String orgDate = "2016-05-19T06:10:00";
    String dstDate = LocalDateTime.parse(orgDate, DateTimeFormatter.ISO_LOCAL_DATE_TIME)
                                  .atZone(ZoneId.of("UTC"))
                                  .withZoneSameInstant(ZoneId.of("CET"))
                                     // CET is deprecated timezone, see list: https://en.wikipedia.org/wiki/List_of_tz_database_time_zones
                                  .format(DateTimeFormatter.ISO_LOCAL_DATE_TIME);
                                            // or use a custom formatter

    System.out.println(orgDate);
    System.out.println(dstDate); 
}

结果:

2016-05-19T06:10:00
2016-05-19T08:10

【讨论】:

  • 对不起,我不明白,因为 java.Util 包中不存在 LocalDateTime,所以它显示错误。
  • @KoneruKiranKumarReddy java.time 包已添加到 Java 8 中。
  • @KoneruKiranKumarReddy 永远不要使用java.time 包之外的日期时间类。切勿使用java.util.DateCalendarSimpleDateFormat 等。它们是糟糕的、糟糕的设计、糟糕的实现,是由不了解日期时间处理复杂性的人构建的。
  • 好答案,除了你打电话给.toLocalDateTime()的部分。 LocalDateTime 类故意缺少任何时区或从 UTC 偏移的概念。所以那个阶级不能代表一个时刻。在调用toLocalDateTime 时,您正在丢弃有价值的信息(时区),从而导致结果模棱两可。虽然您在这里这样做只是作为格式化的捷径,但我认为这是一种坏习惯,滥用类的性质和目的只是为了方便其toString 方法。最好打电话给.format( DateTimeFormatter.ISO_LOCAL_DATE_TIME )
  • @BasilBourque 我同意。我喜欢缺乏toLocalDateTime 转换背后的“哲学”。我编辑了我的答案。
猜你喜欢
  • 2020-09-13
  • 1970-01-01
  • 2020-08-18
  • 1970-01-01
  • 2022-01-11
  • 2016-10-16
  • 1970-01-01
  • 2012-04-01
  • 2019-10-30
相关资源
最近更新 更多