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 w开发者_StackOverflow中文版ay. Any suggestions?
The T inside is because it is the standard ISO format for date http://en.wikipedia.org/wiki/ISO_8601. Mind however that this format with 'T' is only one of several variations you might see when date comes as ISO 8601 (one of the variations is stripped out time, another is with following timezone specicification).
If you know that your date will be conforming to the ISO 8601 standard (this is very often for well-specified XML - when you use XSD date fields conform to ISO 8601) then Java's SimpleDateFormat is not enough - it is too simple... You might revert to JodaTime library instead - Joda Time has already ISO 8601 formatter ready for you to use: http://joda-time.sourceforge.net/api-release/org/joda/time/format/ISODateTimeFormat.html
Edited: I would not implement any complex regexp matching - it makes code difficult to maintain and understand in a long run (especially if you can have many sources in many formats)
The proposal is - find out which provider uses which format and employ strategy pattern: formatter = DateFormatterStrategyChooser.getFormatter(String source). Divide et impera.
And in case you are not 100% sure which source brings what kind of date - you can still use UmbrellaFormatter(Collection) and go through each formatter in sequence until one succeeds.. This is best for maintainability rather than relying on obscure and complex rules.
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.
Test for presence of the 'T', if it it present, parse the string and replace with a space. Now you can use a Date Formatter to create an Date object.
精彩评论