I'm trying to figure out a "simple" way of parsing a String into a Date Object.
The String can be either yyyyMMdd, yyyyMMddHHmm or yyyyMMddHHmmSS.
Currently, I'm looking at the length of the String, and creating a DateParser depending on the length. Is there a more elegant way of doing this?
Or you can pad your string with zeros:
You can use a DateFormatter to parse the Date from the string.
You can change the pattern however you like to reflect your needs.
I would use a
SimpleDateFormat
class, and populate the format pattern based on the length of the string. That'll work fine unless you one day have strings of the same length.Using the examples from your question:
Formatting 11th July 2011:
Formatting 11th July 2011 1340hrs:
Formatting 11th July 2011 1340hrs 10 seconds:
(NB. small s for seconds, capital S is for Milliseconds!)
See the hyperlink for the full list of format pattern letters.
You could still used "specialized" parsers (as you suggested) and chain them: For instance, you can still have a
DateHourMinSecParser
(foryyyyMMddHHmmSS
), aDateHourMinParser
(foryyyyMMddHHmm
) and aDateParser
(foryyyyMMdd
) all of them implementing the same interface:e.g.
but each one of these classes would actually take a parameter another GenericDateParser -- the idea being that each parser would try first to parse the date itself, if the parsing (or some internal checks -- e.g. string length) fails it would then pass it to the next parser in chain until either there are no more parsers in the chain (in which case it would throw an exception, or one of the members in the chain would return a value):
and you would initialize them:
and then just use the top level one:
I would do as you are, looking at the length of the string, and creating an appropriate SimpleDateFormat instance.
NB these are not thread-safe, so you should create a new one each time.