【问题标题】:Convert timestamp coming from a known time zone to the system's time zone将来自已知时区的时间戳转换为系统的时区
【发布时间】:2014-01-20 10:52:42
【问题描述】:
dateFormatterLocal = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
dateFormatterLocal.setTimeZone(TimeZone.getTimeZone("America/New York"));
for (int i = 0; i < list.length; i++) {
    timeStampArrayList.add(dateFormatterLocal.parse(list[i]));
}

我当前的代码没有将已知在 UTC 时区的时间戳转换为我的时区。

我还想知道如何获取系统的当前时区,而不是在可能的情况下告诉它“美国/纽约”。

提前致谢!

【问题讨论】:

  • 我不确定我是否理解这个问题(但有什么新的 ;))。如果您不想指定时区,则需要在格式/String 值中包含时区。如果您无法更改原始值,则可以在解析之前将时区值附加到 String 的末尾...

标签: java timezone


【解决方案1】:

我也不确定我是否完全理解您的问题,但我会尽力为您解答。

我假设您有一个日期作为 UTC 时区的字符串,并且您希望日期作为系统(或您的本地)时区。

为此,只需将字符串 " UTC" 添加到您的时间字符串,并将您的日期格式化程序模式更改为“yyyy-MM-dd HH:mm:ss Z”。这里ZRFC 822 time zone。您也可以使用z,即General time zone

所以你的代码会变成:

String timezoneOffset = " UTC";
dateFormatterLocal = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss Z");  
dateFormatterLocal.setTimeZone(TimeZone.getTimeZone("America/New York"));
for (int i = 0; i < list.length; i++) {
   timeStampArrayList.add(dateFormatterLocal.parse(list[i] + timezoneOffset ));
}

这应该将日期解析为从提供的时区字符串转换而来的格式化程序的时区。


您可以这样做来获取系统当前时区

TimeZone timeZone = Calendar.getInstance().getTimeZone();
System.out.println(timeZone.getDisplayName(false, TimeZone.LONG));

为我打印New Zealand Standard Time - 这是当前时区。

您也可以将TimeZone.LONG 更改为TimeZone.SHORT 以获取缩写版本,即我得到NZST


你也应该阅读this question and answer关于显示日期

【讨论】:

    猜你喜欢
    • 2021-09-22
    • 2011-05-10
    • 2018-12-18
    • 1970-01-01
    • 1970-01-01
    • 2019-05-14
    • 1970-01-01
    • 2013-05-20
    • 2013-06-30
    相关资源
    最近更新 更多