How to detect the given date format using java

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");

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 ?


Apache commons has a utility method to solve this problem . The org.apache.commons.lang.time.DateUtils class has a method parseDateStrictly

   public static Date parseDateStrictly(String str,
                                         String[] parsePatterns)
                                  throws ParseException

 Parameters:
        str - the date to parse, not null
        parsePatterns - the date format patterns to use, see SimpleDateFormat, not null

Parses a string representing a date by trying a variety of different parsers.

The parse will try each parse pattern in turn. A parse is only deemed successful if it parses the whole of the input string. If no parse patterns match, a ParseException is thrown.

The parser parses strictly - it does not allow for dates such as "February 942, 1996".


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()

Tags:

Java

Localdate