Java 如何将 joda 日期时间转换为字符串,反之亦然

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27033965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:41:49  来源:igfitidea点击:

how to convert joda datetime to String and vice versa

javadatetime

提问by rajsekhar

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.

我的问题是,上述方法是否有效或需要使用格式化程序。

采纳答案by Ramzan Zafar

Try this

尝试这个

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

回答by happyvirus

LocalDate localDate = new LocalDate(2010, 9, 14);
DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy");
String formattedDate = formatter.print(localDate);

回答by karfai

For those who want to parse back the value from toStringcan read my answer.

对于那些想要从中解析价值的人toString可以阅读我的答案。

If you to read the implementation of DateTimeclosely. The toStringmethod is override by AbstractInstant.

如果你DateTime仔细阅读执行。该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);