【问题标题】:Java - Convert From A Timezone Different From Local To UTCJava - 从与本地不同的时区转换为 UTC
【发布时间】:2016-02-06 06:08:40
【问题描述】:

所以从我读到的所有关于这个问题的帖子中(例如,Convert timestamp to UTC timezone)。

我了解到进行这种转换的一种方法是:

SimpleDateFormat dfmaputo = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss a");
dfmaputo.setTimeZone(TimeZone.getTimeZone("UTC"));
long unixtime = dfmaputo.parse(data.get(1)).getTime();
unixtime = unixtime / 1000;

output: 
original date (Maputo Timezone) -- 11/5/2015 1:39:45 PM
unix timestamp in UTC --- 1446687585
data.get(1) is the string with the maputo datetime.

我不明白为什么我没有得到 UTC 值。当我转换我期望使用 UTC 的 unix 时间戳时,我得到了带有马普托时区的原始日期时间。

我错过了什么吗?

我是否需要先转换为本地时区,然后再转换为 UTC?

编辑:解决方案

Calendar maputoDateTime = Calendar.getInstance(TimeZone.getTimeZone("Africa/Maputo"));
maputoDateTime.setTimeZone(TimeZone.getTimeZone("GMT"));
Long unixtimeGMT = maputoDateTime.getTimeInMillis() / 1000;

我应该使用日历而不是 SimpleDateFormat。

首先我需要设置输入日期的时区(非洲/马普托),然后将其设置为我需要的时区(GMT)。只有这样我才能得到正确的 unix 时间戳。

感谢@BastiM 回复How to change TIMEZONE for a java.util.Calendar/Date

感谢您的回复和帮助。

【问题讨论】:

    标签: java timezone utc


    【解决方案1】:

    如果您将CAT 时区标识符添加到字符串的末尾并且格式化程序掩码具有z 字母怎么办?如果这就是你总是得到的并且源数据没有给出时区值。

        String sdt = "11/5/2015 11:39:45 PM CAT";
        SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a z", Locale.US);
        Date dt = sdf.parse(sdt);
        Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(dt.getTime());
        System.out.println(dt + ", utc=" + dt.getTime());
        System.out.println(cal);
    

    【讨论】:

      猜你喜欢
      • 2011-09-16
      • 1970-01-01
      • 2011-03-01
      • 2021-04-20
      • 2018-04-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-31
      相关资源
      最近更新 更多