Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to convert joda datetime to String and vice versa

Tags:

java

datetime

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.

like image 322
rajsekhar Avatar asked Nov 20 '14 07:11

rajsekhar


People also ask

What is Joda-Time format?

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.

Does Joda DateTime have time zones?

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.

What is the use of Joda-Time?

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.


2 Answers

Try this

DateTime dt = new DateTime();
DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss");
String dtStr = fmt.print(dt);
like image 59
Ramzan Zafar Avatar answered Sep 27 '22 23:09

Ramzan Zafar


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);
like image 28
karfai Avatar answered Sep 27 '22 23:09

karfai