1
votes

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

1 Answers

0
votes

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