Search code examples
javasimpledateformatdate-formatjava-timedatetime-parsing

Java Date Format that allows - / or . as separators within date


What's the nicest way to parse a date that can be in one of the following formats

 "dd-MM-yyyy HH:mm"
 "dd/MM/yyyy HH:mm"
 "dd.MM.yyyy HH:mm"

without creating 3 SimpleDateFormats and parsing against each one.

Thanks


Solution

  • It's probably easiest to "tweak" the source string into a canonical format:

    if (text.length() == 16)
    {
        if ((text.charAt(2) == '/' && text.charAt(5) == '/') ||
            (text.charAt(2) == '.' && text.charAt(5) == '.'))
        {
            text = text.substring(0, 2) + "-" + text.substring(3, 5) 
               + "-" + text.substring(6);
        }
    }
    

    Then use the format string using "-".

    Note that this is very specific, only replacing exactly the characters you're interested in, to avoid unwanted side-effects.