I have some different format of date to parse but I cannot recognize them with SimpleDateFormat
. Can anybody help me to find patterns for this dates:
- 6 July 1892
- 9 May 1915
- February 335
- 1768-02-12
and
- 23 september 63 bc
- 19 august ad 14
Thanks
I have some different format of date to parse but I cannot recognize them with SimpleDateFormat
. Can anybody help me to find patterns for this dates:
and
Thanks
Joda is generally better if you have to parse using multiple formats. For example,
private static DateTimeFormatter dateFormatter;
String[] validDateFormats = new String[] { "dd-MMM-yyyy HH:mm:ss",
"yyyy-MM-dd HH:mm:ss.SSS" };
DateTimeParser[] parsers = new DateTimeParser[validDateFormats.length];
for (int i = 0; i < validDateFormats.length; ++i) {
parsers[i] = DateTimeFormat.forPattern(validDateFormats[i])
.getParser();
}
dateFormatter = new DateTimeFormatterBuilder().append(null, parsers)
.toFormatter().withZone(DateTimeZone.UTC);
Now this dateFormatter will parse correctly if the input matches any of the formats:
inputDate = dateFormatter.parseDateTime(dateStr);
DateTimeFormatter outputFormat = DateTimeFormat
.forPattern("yyyy/MM/dd");
String outputString = inputDate.toString(outputFormat);
The format strings can be looked up from here: http://joda-time.sourceforge.net/api-release/org/joda/time/format/DateTimeFormat.html
You just provide possibilities of patterns you want your dates to be parsed by and run through them finding the first matching.
Here you can find a great generator for creating every date format you can imagine http://www.fileformat.info/tip/java/simpledateformat.htm
E.g. your first both examples are generated with dd MMMM yyyy ;)
Try these
27-May-2012:
System.out.println(new SimpleDateFormat("d-MMM-YYYY").format(new Date()));
27-05-2012 :
System.out.println(new SimpleDateFormat("d-MM-YYYY").format(new Date()));
27-05-12 :
System.out.println(new SimpleDateFormat("dd-MM-YY").format(new Date()));