简体   繁体   English

使用JODA将RFC 3339从string解析为java.util.Date

[英]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: 假设我有一个为RFC 3339格式化的字符串日期,例如由以下代码生成的“2013-07-04T23:37:46.782Z”:

// 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. 现在我想使用JODA-TIME从我的字符串“2013-07-04T23:37:46.782Z”创建一个java.util.Date。 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): 问题的实际答案(Yori:您使用ISODateTimeFormat是对的,但您的代码/接受的答案会进行格式化,而不是解析):

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. 希望它可以帮助别人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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