Charlie Charlie - 2 months ago 5x
Java Question

How do I convert 2010-12-15T16:26:49.841-08:00 to a GregorianCalendar in Java?

I have a string date "2010-12-15T16:26:49.841-08:00" and I need to convert it to a GregorianCalendar in Java. How do you do this?

Solution from Jesper's answer

Code for the solution using joda time:

DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ").withOffsetParsed();
DateTime date = formatter.parseDateTime("2010-12-15T16:26:49.841-08:00");


Unfortunately, the standard SimpleDateFormat class cannot handle ISO 8601 format very well. Specifically, it cannot handle the : that is in the timezone offset at the end.

What you can do is manually remove the : from the timezone offset, so that you get a string that looks like this:


(note that the timezone offset is -0800 instead of -08:00). Then you can parse it with SimpleDateFormat with the format yyyy-MM-dd'T'HH:mm:ss.SSSZ.

But it is better to use the popular Joda-Time library to handle times and dates; it is much better than the standard Java API date and calendar classes and handles ISO 8601 format properly.