I want to find the count between two dates in java but dates should be accepted whatever may be the date formats.Need to give two dates as parameters to a method which can be of different formats but whatever may be the format typed by the user, it can be "dd/M/yyyy" or "MM/dd/yyyy" or anything, it should be accepted.This is the requirement.
-
What do you want to count between the two dates? Number of days, or what? – Mushif Ali Nawaz Nov 19 '19 at 09:24
-
2But the problem is, that you can't parse the date in any format without knowing the format of the date, beforehand. Let's say the user enters `01/05/2019`, how would you know whether it's `dd/MM/yyyy` or `MM/dd/yyyy`? Since it can be parsed in both of these formats! – Mushif Ali Nawaz Nov 19 '19 at 09:26
-
Want to count the number of days – Christina Isac Anil Nov 19 '19 at 09:31
-
Where are those dates? You should store them as date, not as string, to prevent these problems. – Hans Kesting Nov 19 '19 at 09:55
1 Answers
Parsing Date in any format is a very complex task and frankly not possible to have 100% accurate. Consider this date 07/08/2010 - It could be Aug 7th or July 8th of 2010 and without additional info, it is impossible to say which one it is. I once dealt with the task of parsing a Date in any format. My idea was that you write in an external file a list of all formats that you want to support and place them in order that you want to be considered. Then in your code, you take the string to be parsed and try to parse it against your formats one by one until you succeed and if none of them fit then you declare the string not to be a valid date. The advantages of this idea are that you can add or remove different formats without changing your code. You can have different lists for different customers. Changing the order of the list you can prioritize and determine if your string fits more then one format which one will be taken. In our example with 07/08/2010 for US-based implementation you would place MM/dd/YYYY before dd/MM/YYYY but for European implementation, you would place the formats in reverse order. That's the idea. Here is the link to the article where I described the idea in more detail with some example for the list of the formats: Java 8 java.time package: parsing any string to date

- 7,315
- 2
- 19
- 36