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 时区时间戳转换为我的时区。
我还想知道如何获取系统当前的时区,而不必告诉它“美国/纽约”(如果可能的话)。
提前致谢!
最佳答案
我也不确定我是否完全理解您的问题,但我会尽力为您解答。
我假设您有一个采用 UTC 时区的字符串形式的日期,并且您希望该日期为系统(或您本地)时区。
为此,只需将字符串 "UTC"
添加到您的时间字符串中,并将日期格式化程序模式更改为“yyyy-MM-dd HH:mm:ss Z”。这里Z
是RFC 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));
它为我打印新西兰标准时间
- 这是当前时区。
您还可以将 TimeZone.LONG
更改为 TimeZone.SHORT
以获得缩写版本,即我得到 NZST
您还应该阅读this question and answer关于显示日期
关于java - 将来自已知时区的时间戳转换为系统时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21224998/