Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 213
Tarski Avatar asked Sep 18 '09 09:09

Tarski


2 Answers

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.

like image 71
Jon Skeet Avatar answered Sep 30 '22 13:09

Jon Skeet


Could you run two replace operations first, so that you reduce all three formats to a single one?

like image 32
kgiannakakis Avatar answered Sep 30 '22 15:09

kgiannakakis