For the project I’m working on at the moment I need to convert a String to a Date. Unfortunately the date and time aren’t formatted the same in all the Strings that need to be converted. In the current values we often see something like 2011-06-25T22:44:12 or 2011-06-25 22:49:01 (notice the T?).
I know how to convert a String to a Date using SimpleDateFormat, but since I don’t know what the format the input will have this doesn’t seem like the right approach. I was wondering if there is a way to add several ‘formats’ to a DateFormat object or perhaps there’s a DateFormat class that can auto-detect the format?
The other approach I was thinking of is using some if/else statements and regular expressions on the String to figure out what format is being used and use the SimpleDateFormat class that matches with it, but I’m pretty sure there should be an easier way. Any suggestions?
If you have several variations, not just one with ‘T’ and another with a space, I believe an if/then/else with several regular expressions and matching SimpleDateFormats is the way to go.