Converting String in ISO8601 T-Z format to Date

user2511713 picture user2511713 · Jul 17, 2013 · Viewed 44.4k times · Source

Possible Solution:Convert Java Date into another Time as Date format

I went through it but does not get my answer.

I have a string "2013-07-17T03:58:00.000Z" and I want to convert it into date of the same form which we get while making a new Date().Date d=new Date();

The time should be in IST Zone - Asia/Kolkata

Thus the date for the string above should be

Wed Jul 17 12:05:16 IST 2013 //Whatever Time as per Indian Standard GMT+0530

String s="2013-07-17T03:58:00.000Z";
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); 
TimeZone tx=TimeZone.getTimeZone("Asia/Kolkata");
formatter.setTimeZone(tx);
d= (Date)formatter.parse(s);

Answer

Mark M picture Mark M · Jul 17, 2013

Use calendar for timezones.

TimeZone tz = TimeZone.getTimeZone("Asia/Calcutta");
Calendar cal = Calendar.getInstance(tz);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'")
sdf.setCalendar(cal);
cal.setTime(sdf.parse("2013-07-17T03:58:00.000Z"));
Date date = cal.getTime();

For this however I'd recommend Joda Time as it has better functions for this situation. For JodaTime you can do something like this:

DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
DateTime dt = dtf.parseDateTime("2013-07-17T03:58:00.000Z");
Date date = dt.toDate();