Java-从不同于本地的时区转换为UTC
所以从我读到的所有关于这个问题的帖子(例如,) 我了解到进行这种转换的一种方法是:Java-从不同于本地的时区转换为UTC,java,timezone,utc,Java,Timezone,Utc,所以从我读到的所有关于这个问题的帖子(例如,) 我了解到进行这种转换的一种方法是: 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;
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),我得到了原始的带有马普托时区的日期时间
我错过什么了吗
我是否需要先转换为本地时区,然后再转换为UTC
编辑:解决方案
Calendar maputoDateTime = Calendar.getInstance(TimeZone.getTimeZone("Africa/Maputo"));
maputoDateTime.setTimeZone(TimeZone.getTimeZone("GMT"));
Long unixtimeGMT = maputoDateTime.getTimeInMillis() / 1000;
我应该使用日历而不是SimpleDataFormat
首先,我需要设置输入日期的时区(非洲/马普托),然后将其设置为我需要的时区(GMT)。只有这样,我才能得到正确的unix时间戳
感谢@BastiM的回复
感谢您的回复和帮助。如果您在字符串末尾添加
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);
如果将
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);