How to Parse Date from GMT TimeZone to IST TimeZone and Vice Versa in android

Amritpal Singh picture Amritpal Singh · Jan 14, 2013 · Viewed 64.9k times · Source

I am working on a project that fetches Date/Time from backend in IST(Indian standard Time) as shown "2013-01-09T19:32:49.103+05:30". However when i parse it using following DateFormat

DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

followed by parsing..

Date date = sdf.parse("2013-01-09T19:32:49.103+05:30");


System.out.println("XYZ ==============>"+date);

its Displaying date in GMT format as output i.e

Wed Jan 09 14:02:49 GMT+00:00 2013.

I have tried it using TimeZone class as..

TimeZone timeZone=TimeZone.getTimeZone("IST");
sdf.setTimeZone(timeZone);

but no effect..

How could i get a Date class Object having Date in IST format instead of GMT...

Please provide an appropriate solution..

EDIT:

This is how Code Looks Like:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");

TimeZone timeZone=TimeZone.getTimeZone("IST");
sdf.setTimeZone(timeZone);

Date date = sdf.parse("2013-01-09T19:32:49.103+05:30");
String formattedDate=sdf.format(date);

System.out.println("XYZ ==============>"+formattedDate);

Answer

Evgeniy Dorofeev picture Evgeniy Dorofeev · Jan 14, 2013

Date does not have any time zone. It is just a holder of the number of milliseconds since January 1, 1970, 00:00:00 GMT. Take the same DateFormat that you used for parsing, set IST timezone and format your date as in the following example

    DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
    Date date = sdf.parse("2013-01-09T19:32:49.103+05:30"); 
    sdf.setTimeZone(TimeZone.getTimeZone("IST"));
    System.out.println(sdf.format(date));

output

2013-01-09T19:32:49.103+05:30

Note that XXX pattern is used for ISO 8601 time zone (-08:00) since 1.7. If you are in 1.6 try Z. See SimpleDateFormat API for details of format patterns