SimpleDateFormat Joda-Time Apache-DateUtils parses the similarities and differences between ISO8601 date strings, jodatime
Put the following code directly:
Import part:
1 1 import java. util. date; 2 2 import java. text. simpleDateFormat; 3 3 import org. apache. commons. lang3.time. dateUtils; 4 4 import org. joda. time. dateTime; 5 5 import org. joda. time. format. dateTimeFormat;View Code
Conversion part
1 String datestr1 = "2016-06-07T14: 08: 09.235 + 08: 00"; // ISO8601 2 String datestr2 = "14:08:09"; // Without Millis 3 String datestr3 = "14:08:09. 235 "; // With Millis 4 5 // Joda Time 6 Date date0 = new DateTime (datestr1 ). toDate (); 7 Date date1 = DateTimeFormat. forPattern ("yyyy-MM-dd't'hh: mm: ss. SSSZZ "). parseDateTime (datestr1 ). toDate (); 8 Date date2 = DateTimeFormat. forPattern ("yyyy-MM-dd HH: mm: ss "). parseDateTime (datestr2 ). toDate (); 9 Date date3 = DateTimeFormat. forPattern ("yyyy-MM-dd HH: mm: ss. SSS "). parseDateTime (datestr3 ). toDate (); 10 11 // JDK12 date1 = new SimpleDateFormat ("yyyy-MM-dd't'hh: mm: ss. SSSXXX "). parse (datestr1); // XXX means Timezone for Java SimpleDateFormat13 date2 = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss "). parse (datestr2); 14 date3 = new SimpleDateFormat ("yyyy-MM-dd HH: mm: ss. SSS "). parse (datestr3); 15 16 // Apache17 date1 = DateUtils. parseDate (datestr1, "yyyy-MM-dd't'hh: mm: ss. SSSZZ "); 18 date2 = DateUtils. parseDate (datestr2, "yyyy-MM-dd HH: mm: ss"); 19 date3 = DateUtils. parseDate (datestr3, "yyyy-MM-dd HH: mm: ss. SSS ");View Code
Three Common Format date strings are used in the test, including Json conversion default ISO8601 format. SimpleDateFormat Joda-Time Apache-DateUtils can be used to parse the three date formats:
1. SimpleDateFormat parses the ISO8601 format string as "yyyy-MM-dd't'hh: mm: ss. SSSXXX". XXX indicates the time zone, which is different from the common ZZ format.
2. the default format of Joda-Time is ISO8601, so you can directly use new DateTime (...) the method of parsing the ISO8601 date string directly. Of course, you can also use the Date Format String for parsing. The code for parsing the date with the date format string is slightly longer.
3. the format string used by Apache-DateUtils to parse ISO8601 is "yyyy-MM-dd't'hh: mm: ss. SSSZZ ", parsing code is more concise than Joda-Time.
To put it bluntly: SimpleDateFormat uses XXX to indicate that the time zone is really abnormal. It takes me half a day to complete it. We hereby record it.