Search code examples
javadateiso8601

Parsing a timestamp containg the date, time & offset


I'm using using Java 5.

I need to parse date-time strings in ISO 8601 format such as 2011-11-30T12:00:00.000+00:00:

String dateString = "2011-11-30T12:00:00.000+00:00";
DateFormat df = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ"); 
Date parsed=null;
try {
    parsed = df.parse(dateString);
}

I have also tried this pattern: yyyy-MM-dd'T'HH:mm:ss.SSSz, but get same result:

java.text.ParseException: Unparseable date: "2011-11-30T12:00:00.000+00:00"

Any ideas?


Solution

  • Joda-Time

    You have to use Joda-Time (Maven) (supports Java 1.5) if you don't want to parse it manually. Just create an object with new DateTime(String) then you can get Date via toDate() method.

    Time Zone

    Pass the time zone you want assigned to the resulting date-time object. Unlike java.util.Date, a Joda-Time DateTime object knows its own assigned time zone (DateTimeZone). If omitted, the JVM’s current default time zone is assigned implicitly.

    DateTimeZone zone = DateTimeZone.forID( "America/Montreal" ); // Or perhaps DateTimeZone.UTC
    DateTime dateTime = new DateTime( "2011-11-30T12:00:00.000+00:00", zone );