Muhammad Umar
Muhammad Umar

Reputation: 11782

Converting UTC date from server into local time

I am getting this string as Date from Server

2016-06-11T11:14:57.000Z

Since it is UTC, I want to convert to my local time.

SimpleDateFormat mFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
SimpleDateFormat endFormat = new SimpleDateFormat("hh:mm a");
mFormat.setTimeZone(TimeZone.getTimeZone("GMT+5:00"));
Date date = mFormat.parse(mBooking.startTime);

However the date converted to 2:00AM

Now i don't get it why 11am is getting converted to 2:00AM

What wrong am i doing?

Upvotes: 0

Views: 59

Answers (1)

Nicolas Filotto
Nicolas Filotto

Reputation: 44965

Because you don't set the timezone properly to each SimpleDateFormat indeed mFormat should be set to UTC and endFormat to GMT + 5, here is what you are supposed to do:

SimpleDateFormat mFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
// Set UTC to my original date format as it is my input TimeZone
mFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
Date date = mFormat.parse("2016-06-11T11:14:57.000Z");
SimpleDateFormat endFormat = new SimpleDateFormat("hh:mm a");
// Set GMT + 5 to my target date format as it is my output TimeZone
endFormat.setTimeZone(TimeZone.getTimeZone("GMT+5:00"));

System.out.println(endFormat.format(date));

Output:

04:14 PM

Upvotes: 3

Related Questions