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.
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.
An interval in Joda-Time represents an interval of time from one instant to another instant. Both instants are fully specified instants in the datetime continuum, complete with time zone.
Joda-Time provides support for multiple calendar systems and the full range of time-zones. The Chronology and DateTimeZone classes provide this support. Joda-Time defaults to using the ISO calendar system, which is the de facto civil calendar used by the world.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With