Search code examples
javadatetimedate-format

Getting date from unknown Date format string


If i have a string that contain a date in a format (unknown) "d/MM/YY" or "m:d:YYYY" etc.).

How could i parse it and get day,month,year values ?

I tried to parse them by filling an array with all format combinations , and try to parse the date with each one of them , i think it's a stupid solution !

Any ideas ?


Solution

  • your best bet is to use natty

    very useful library,

    here is an example of how to use it:

    public static Date parse(String date) throws Exception {
    
        try{
    
            List<DateGroup> parse = new PrettyTimeParser().parseSyntax(date);
            return parse.get(0).getDates().get(0);
    
        }catch (Exception e){
            throw new Exception("unparseable date: " + date);
        }
    
    }