how to convert dateTime type to gregorianCalendar

vjk picture vjk · May 29, 2012 · Viewed 10.1k times · Source

I am getting time in string like this "2011-02-27T10:03:33.099-06:00" which is of xml dateTime type. I also have timezone of TimeZone type. How should I convert the dateTime to GregorianCalendar java type in that timezone.

Answer

user unknown picture user unknown · May 29, 2012
sdf = new java.text.SimpleDateFormat ("yyyy-MM-dd'T'HH:mm:ss.S");

parses everything, except the trailing TZ.

sdf.parse (sd);
res168: java.util.Date = Sun Feb 27 10:03:33 CET 2011

From the api docs, I would expect

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

to be used to read the -06:00 in the end. But I see, that there is either an offset in the form 0700 expected, or with a prefix of GMT for example "GMT-04:00". So you have to insert that GMT-thingy yourself:

sdf.parse (sd.replaceAll ("(......)$", "GMT$1"))

SDF.parse (str) returns a Date, which has to be converted into a GC:

GregorianCalendar calendar = new GregorianCalendar ();
calendar.setTime (date);