2015-11-05 99 views
1

因此,从我读过的关于此问题的所有帖子(例如Convert timestamp to UTC timezone)中了解到。Java - 从不同于本地的时区转换为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; 

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时区获得原始日期时间。

我错过了什么吗?

我是否需要先转换到本地时区而不是UTC?

编辑:解

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

相反的SimpleDateFormat的,我应该使用的日历。

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

多亏How to change TIMEZONE for a java.util.Calendar/Date

@BastiM回复谢谢您的回复和帮助。

回答

0

如果将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); 
相关问题