Java - 从不同于本地的时区转换为 UTC [英] Java - Convert From A Timezone Different From Local To UTC
问题描述
所以从我读到的关于这个问题的所有帖子(例如,将时间戳转换为 UTC 时区).
So from all the posts I read about this issue (for example, Convert timestamp to UTC timezone).
我了解到进行这种转换的方法是:
I learn that a way to do this conversion is :
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 值.当我转换 unix 时间戳时,我希望在 UTC 中使用 Maputo 时区.
I don't understand why I'm not getting the UTC value. When I convert the unix timestamp, that I was expecting to be in UTC, I get the original datetime with Maputo Timezone.
我错过了什么吗?
我是否需要先转换为本地时区,然后再转换为 UTC?
Do I need to convert first to my local timezone and than to UTC?
解决方案
Calendar maputoDateTime = Calendar.getInstance(TimeZone.getTimeZone("Africa/Maputo"));
maputoDateTime.setTimeZone(TimeZone.getTimeZone("GMT"));
Long unixtimeGMT = maputoDateTime.getTimeInMillis() / 1000;
我应该使用日历而不是 SimpleDateFormat.
Instead of SimpleDateFormat I should use Calendar.
首先,我需要设置输入日期的时区 (Africa/Maputo),然后将其设置为我需要的时区 (GMT).只有这样我才能得到正确的 Unix 时间戳.
First I needed to set the input date's timezone (Africa/Maputo) and then set it to the one I needed (GMT). And only then I could get the correct unix timestamp.
感谢@BastiM 在如何更改java.util.Calendar/Date 的 TIMEZONE
Thanks to @BastiM reply in How to change TIMEZONE for a java.util.Calendar/Date
感谢您的回复和帮助.
推荐答案
如果在字符串末尾添加 CAT
时区标识符并且格式化程序掩码有 z
字母怎么办?如果那是你总是得到的,而源数据没有给出时区值.
What if you add CAT
timezone identifier to the end of string and formatter mask has z
letter? If thats what you always get and source data does not give timezone value.
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);
这篇关于Java - 从不同于本地的时区转换为 UTC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!