Java - Convert From A Timezone Different From Local To UTC

[亡魂溺海] 提交于 2019-12-11 11:55:30

问题


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.

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.

Am I missing something?

Do I need to convert first to my local timezone and than to UTC?

EDIT: Solution

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

Instead of SimpleDateFormat I should use Calendar.

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.

Thanks to @BastiM reply in How to change TIMEZONE for a java.util.Calendar/Date

Thank you for your replies and help.


回答1:


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);


来源:https://stackoverflow.com/questions/33544022/java-convert-from-a-timezone-different-from-local-to-utc

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!