简体   繁体   English

如何将joda datetime转换为String,反之亦然

[英]how to convert joda datetime to String and vice versa

Is there a way to convert Joda DateTime to String and then from that String to DateTime. 有没有办法将Joda DateTime转换为String,然后从该String转换为DateTime。

DateTime d = ..;
String date = d.toString();
DateTime dateTime = DateTime.parse(date);

My question is that whether the above approach is valid or need to use formatter. 我的问题是上述方法是否有效或需要使用格式化程序。

Try this 试试这个

DateTime dt = new DateTime();
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
String dtStr = fmt.print(dt);

For those who want to parse back the value from toString can read my answer. 对于那些想要解析toString值的人可以阅读我的答案。

If you to read the implementation of DateTime closely. 如果你仔细阅读DateTime的实现。 The toString method is override by AbstractInstant . toString方法被AbstractInstant覆盖。

@ToString
public String toString() {
    return ISODateTimeFormat.dateTime().print(this);
}

Now, parse the value from toString : 现在,解析toString的值:

DateTime dt = new DateTime();
String dtStr = dt.toString();
DateTimeFormatter fmt = ISODateTimeFormat.dateTime();
DateTime newDt = fmt.parse(dtStr);
LocalDate localDate = new LocalDate(2010, 9, 14);
DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy");
String formattedDate = formatter.print(localDate);

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

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