Rafa
Rafa

Reputation: 2027

Parse RFC 3339 from string to java.util.Date using JODA

Let's suppose that I have a date as string formatted for RFC 3339 such as "2013-07-04T23:37:46.782Z" generated by the code below:

// This is our date/time
Date nowDate = new Date();
// Apply RFC3339 format using JODA-TIME
DateTime dateTime = new DateTime(nowDate.getTime(), DateTimeZone.UTC);
DateTimeFormatter dateFormatter = ISODateTimeFormat.dateTime();
String dateString = dateFormatter.print(dateTime);
System.out.println("Server side date (RFC 3339): " + dateString );
// Server side date (RFC 3339): 2013-07-04T23:37:46.782Z

Now I want to create a java.util.Date from my string "2013-07-04T23:37:46.782Z" using JODA-TIME. How do I achieve that?

Upvotes: 6

Views: 6622

Answers (2)

Nilzor
Nilzor

Reputation: 18593

Actual answer to question (Yori: you're right in using ISODateTimeFormat, but your code/accepted answer does formatting, not parsing):

public static java.util.Date Rfc3339ToDateThroughJoda(String dateString) {
    DateTimeFormatter dateFormatter = ISODateTimeFormat.dateTime();   
    DateTime dateTime = dateFormatter.parseDateTime(dateString);    
    return dateTime.toDate();
}

Upvotes: 6

Rafa
Rafa

Reputation: 2027

Alright, I found the solution. It was right under my nose.

// Apply RFC3339 format using JODA-TIME
DateTime dateTime = new DateTime("2013-07-04T23:37:46.782Z", DateTimeZone.UTC);
DateTimeFormatter dateFormatter = ISODateTimeFormat.dateTime();

Hopefully it can help someone else.

Upvotes: 5

Related Questions