Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 457
iliaden Avatar asked Dec 22 '22 11:12

iliaden


1 Answers

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")));
like image 52
Howard Avatar answered Jan 29 '23 06:01

Howard