java - Check DateInString format before formatting -
my incoming data have dates in string supposed format following format "dd/mm/yyyy". able convert date correct format with:
simpledateformat sdf = new simpledateformat("dd/mm/yyyy"); //new format simpledateformat sdf2 = new simpledateformat("yyyy/mm/dd"); //old format string dateinstring = "2013/10/07" //string might in different format try{ date date = sdf2.parse(dateinstring); system.out.println(sdf.format(date)); } catch (parseexception e){ e.printstacktrace(); }
however, have strings in different format such 2013/10/07, 07/10/2013, 10/07/2013, 7 jul 13. how compare them before formatting individually?
i found check date format before parsing pretty similar cannot comprehend it.
thank you.
i create utility class, has list of supported formats , method tries convert given string
object date
.
public class dateutil { private static list<simpledateformat> dateformats; static { dateformats = new arraylist<simpledateformat>(); dateformats.add(new simpledateformat("yyyy/mm/dd")); dateformats.add(new simpledateformat("dd/m/yyyy")); dateformats.add(new simpledateformat("dd/mm/yyyy")); dateformats.add(new simpledateformat("dd-mmm-yyyy")); // add more, if needed. } public static date converttodate(string input) throws exception { date result = null; if (input == null) { return null; // or throw exception, if wish } (simpledateformat sdf : dateformats) { try { result = sdf.parse(input); } catch (parseexception e) { //caught if format doesn't match given input string } if (result != null) { break; } } if (result == null) { throw new exception("the provided date not of supported format"); } return result; } }
Comments
Post a Comment