简体   繁体   中英

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?

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();
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM