Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

jodatime

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?

like image 847
Rafa Avatar asked Jul 04 '13 23:07

Rafa


People also ask

How to convert String to JODA DateTime in Java?

Parsing String to Date in Java using Joda TimeCreate a date pattern using forPattern() method of DateTimeFormat class. forPattern() method returns an object of DateTimeFormatter which does actual parsing. Use parseMillis() method of DateTimeFormatter class to convert String to long millisecond.

What is Joda time format?

Joda-Time provides a comprehensive formatting system. There are two layers: High level - pre-packaged constant formatters. Mid level - pattern-based, like SimpleDateFormat. Low level - builder.

What is rfc3339?

ISO 8601, RFC 2822 and RFC 3339 are a standards for date and time representation covering the formatting of date and time (with or without possible fractional seconds) and timezone information.

Does Java Util date store milliseconds?

Conclusion. Class java. util. Date stores a date-time value as milliseconds since the epoch.


1 Answers

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();
}
like image 64
Nilzor Avatar answered Sep 19 '22 01:09

Nilzor