-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
4
  • 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. Commented Apr 5, 2017 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. Commented Apr 5, 2017 at 21:36
  • 3
    How to parse dates in multiple formats using SimpleDateFormat Commented Apr 5, 2017 at 21:39
  • 1
    why don't you just try ... str.replaceAll("-","//"); ? Commented Apr 5, 2017 at 21:39

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.