1

How can I identify the date format by passing the input date

4/17/2018

17/4/2018

2018/17/4

2018/04/17

sekhar
  • 175
  • 2
  • 13
  • 3
    You can match the input against various regex patterns but there's no way to tell the difference between American Feb. 1st (2/1/2018) and European 2nd of Jan. (2/1/2018). Year abbreviations (11/12/13) are also a problem. – jwvh Apr 17 '18 at 07:09
  • 2
    There are also Java libraries available for this. Mentioned [here](https://stackoverflow.com/questions/13230360/string-date-to-javascript-date-parse-date) and [here](https://stackoverflow.com/questions/3389348/parse-any-date-in-java) and [here](https://stackoverflow.com/questions/29649241/how-to-check-if-string-contains-a-only-date-format-in-java). – jwvh Apr 17 '18 at 07:15
  • The easiest way is to build a list will all the possible formats (shouldn't be many) and try to format them one by one until one matches properly – SCouto Apr 17 '18 at 07:29
  • 2018/17/4 isn’t really used. Are you sure you can have this? The other there are all commonplace. – Ole V.V. Apr 17 '18 at 11:06
  • Similar questions have been asked and answered many times. [One example here: How to parse dates in multiple formats using SimpleDateFormat](https://stackoverflow.com/questions/4024544/how-to-parse-dates-in-multiple-formats-using-simpledateformat). Search for more. In any case, unless you realize it’s not possible, I recommend looking into [the Java tutorial section on date and time parsing and formatting](https://docs.oracle.com/javase/tutorial/datetime/iso/format.html) (since you can use Java classes in Scala). – Ole V.V. Apr 17 '18 at 11:08

1 Answers1

1

As explained in the comments, you need to check each different date format in turn until you get a valid date.

The order in which you check the different formats will depend on where the date came from. See here for the preference in different countries, but be aware that the US is really the only place that uses MDY and YDM. Elsewhere the ISO standard YMD or DMY are used.

So for the US you probably want MDY DMY YMD YDM, for China you want YMD DMY and for the rest of the world DMY YMD.

The order in which you check dates should ideally be a regional option in your system.

Tim
  • 26,753
  • 2
  • 16
  • 29