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 whether the above approach is valid or should I use a formatter.

+7
java datetime
source share
3 answers

try it

 DateTime dt = new DateTime(); DateTimeFormatter fmt = DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"); String dtStr = fmt.print(dt); 
+11
source share
 LocalDate localDate = new LocalDate(2010, 9, 14); DateTimeFormatter formatter = DateTimeFormat.forPattern("MM/dd/yyyy"); String formattedDate = formatter.print(localDate); 
0
source share

For those who want to parse the return value from toString , you can read my answer.

If you carefully read the implementation of DateTime . The toString method is overridden by AbstractInstant .

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

Now analyze the value from toString :

 DateTime dt = new DateTime(); String dtStr = dt.toString(); DateTimeFormatter fmt = ISODateTimeFormat.dateTime(); DateTime newDt = fmt.parse(dtStr); 
0
source share

All Articles