How to detect the given date format using java

Ramesh picture Ramesh · Jul 3, 2012 · Viewed 23.3k times · Source

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;
    }

Answer

Brian Agnew picture Brian Agnew · Jul 3, 2012

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 ?