Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a timestamp containg the date, time & offset

Tags:

java

date

iso8601

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?

like image 620
robert trudel Avatar asked Jan 01 '26 21:01

robert trudel


2 Answers

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 );
like image 98
Ruslan Ostafiichuk Avatar answered Jan 03 '26 11:01

Ruslan Ostafiichuk


You should remove the colon from +00:00, as this format only works with the X pattern, which is not available in Java 5, only from Java SE 7.

More information: RFC822 needs this style (without colon), in ISO 8601 both is correct.

like image 38
meskobalazs Avatar answered Jan 03 '26 11:01

meskobalazs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!