简体   繁体   中英

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.

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.

If you to read the implementation of DateTime closely. The toString method is override by AbstractInstant .

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

Now, parse the value from 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);

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