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?

Answer

Or you can pad your string with zeros:

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

System.out.println(sdf.format(sdf.parse("20110711182405")));
System.out.println(sdf.format(sdf.parse("201107111824")));
System.out.println(sdf.format(sdf.parse("20110711")));

Leave a Reply

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