I have a method that gets a string and change that to a particular date format but the thing is the date will be any format For Example
16 July 2012
March 20 2012
2012 March 20
So I need to detect the string is in which file format.
I use the below code to test it but I get exception if the file format changes.
private String getUpdatedDate(String updated) {
Date date;
String formatedDate = null;
try {
date = new SimpleDateFormat("d MMMM yyyy", Locale.ENGLISH)
.parse(updated);
formatedDate = getDateFormat().format(date);
} catch (ParseException e) {
e.printStackTrace();
}
return formatedDate;
}
Perhaps the easiest solution is to build a collection of date formats you can reasonably expect, and then try the input against each one in turn.
You may want to flag ambiguous inputs e.g. is 2012/5/6 the 5th June or 6th May ?
BalusC wrote a simple DateUtil
which serves for many cases. You may need to extend this to satisfy your requirements.
Here is the link: https://balusc.omnifaces.org/2007/09/dateutil.html
and the method you need to look for determineDateFormat()
If you're using Joda Time (awesome library btw) you can do this quite easily:
DateTimeParser[] dateParsers = {
DateTimeFormat.forPattern("yyyy-MM-dd HH").getParser(),
DateTimeFormat.forPattern("yyyy-MM-dd").getParser() };
DateTimeFormatter formatter = new DateTimeFormatterBuilder().append(null, dateParsers).toFormatter();
DateTime date1 = formatter.parseDateTime("2012-07-03");
DateTime date2 = formatter.parseDateTime("2012-07-03 01");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With