How to parse ambiguous String into Date?

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:

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmSS") {
  public Date parse(String s) throws ParseException {
    return super.parse((s + "000000").substring(0, 14));


Leave a Reply

Your email address will not be published. Required fields are marked *