Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

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

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);
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...