【发布时间】: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
感谢您的回复和帮助。
【问题讨论】: