-1

In Java we can use SimpleDateFormat to parse a date like below:

SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy");
Date d = sdf.parse("12/21/2012"); //matched to December 21, 2012

but if our date changes to

Date d = sdf.parse("12-21-2012"); //ParseException!!

is there an easy way to expand this functionality to all sets of numbers by intermixing a regex? In other words, I don't care what the delimiter(s) are as long as the format matches. E.G:

SimpleDateFormat sdf = new SimpleDateFormat("MM[^0-9]dd[^0-9]yyyy");
Date d = sdf.parse("12/21/2012"); //matched to December 21, 2012
Date d = sdf.parse("12-21-2012"); //matched to December 21, 2012
HedonicHedgehog
  • 592
  • 1
  • 6
  • 17
  • 1
    I cannot more strongly advise against using the legacy `java.util.Date` class. You should find the appropriate class for your use case in the `java.time` package. – Joe C Apr 05 '17 at 21:35
  • You can't do this directly, but perhaps you want to create your own class that extends the abstract parent class of SimpleDateFormat: DateFormat. – Hovercraft Full Of Eels Apr 05 '17 at 21:36
  • 3
    [How to parse dates in multiple formats using SimpleDateFormat](http://stackoverflow.com/questions/4024544/how-to-parse-dates-in-multiple-formats-using-simpledateformat) – Pshemo Apr 05 '17 at 21:39
  • 1
    why don't you just try ... str.replaceAll("-","//"); ? – Dieter Apr 05 '17 at 21:39

1 Answers1

0

You cannot use java.text.SimpleDateFormat with generic format. You need to have a clearly defined format when you want to parse or format a java.util.Date.