How do I change simpledateformat to jodatime?
I need to change simpledateformat to another format, which is equivalent in jodatime
public static String dateFormat(Date date,String format) { SimpleDateFormat sdf = new SimpleDateFormat(format); return sdf.format(date); }
I tried using datetimeformatter
public static String dateFormat(DateTime date,String format) { DateTimeFormatter dtf = DateTimeFormat.forPattern(format); DateTime tempDateTime = dtf.parseDateTime(date.toString()); return tempDateTime.toString(); }
But I got it wrong
Solution
Well, I found you in the documents of joda time and simpledateformat As you can see there, unfortunately the schema definitions are not the same If you translate from simpledateformat to joda - datetimeformat, you must pay attention to the following:
Change y to X (so-called week – year)
Change y to y (age) and possibly change the chronology (from ISO to Gregory / Julian)
Joda time (month) does not support W, so it does not need to be replaced!
F is not supported in joda time (day of the week), so there is no need to replace it!
Change java to e (weeks – ISO orders, not localized), available from Java 7
The symbol s is handled differently (I think it's better in joda time because of the correct zero padding)
The zone symbol Z does not allow parsing in joda time (this may be the current cause of your problem - you have not displayed your schema format or your exceptions)
The area / offset symbol Z is handled better in joda time, such as allowing colons in colons, etc If you need the latter, you can use X in simpledateformat, which has a replacement Z in joda time
Some tests added:
The following example code demonstrates the different handling of the format symbol s
String s = "2014-01-15T14:23:50.026"; DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSS"); DateTime instant = dtf.parseDateTime(s); System.out.println(dtf.print(instant)); // 2014-01-15T14:23:50.0260 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSS"); Date date = sdf.parse(s); System.out.println(sdf.format(date)); // 2014-01-15T14:23:50.0026 (bad!)
Another test of format symbol Z (your question???):
String s = "2014-01-15T14:23:50.026PST"; DateTimeFormatter dtf = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSSz"); DateTime instant = dtf.parseDateTime(s); System.out.println(dtf.print(instant)); // abort Exception in thread "main" java.lang.IllegalArgumentException: Invalid format: "2014-01-15T14:23:50.026PST" is malformed at "PST" at org.joda.time.format.DateTimeFormatter.parseDateTime(DateTimeFormatter.java:866) at time.JodaTest8.main(JodaTest8.java:83)
Simpledateformat can perform this zone name resolution (although sometimes at least dangerous):
String s = "2014-01-15T14:23:50.026PST"; SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSz"); Date date = sdf.parse(s); System.out.println(sdf.format(date)); // 2014-01-15T14:23:50.026PST