Question

I am facing an issue with parsing/converting a dateString from browser to Date format in Java. The following are some of the values that I got from the browser.

dateStr = "01-01-2010 05:06:22";
dateStr = "Mon Oct 11 07:00:00 EDT 2010";
dateStr = "Fri May 25 2012 08:00:00 GMT-0400 (Eastern Daylight Time)";

Each dateStr is in different format and at the back-end I was using a SimpleDateFormat with a particular format to convert dateStr. Since the input dateStr format is not consistent, any idea about how this can be handled in the backend?

There is little access to the frontend code/folks.

PS: I did google about this and read the related topics here on StackOverflow.

Any sort of help is greatly appreciated. Thank you.

Was it helpful?

Solution

You have all the pieces you need. First define patterns for every possible date format you can get from the client. Then simply iterate over these formats and try parsing input using each of them and SimpleDateFormat.

Continue looping if SimpleDateFormat returns null (parse error) until you get valid Date. You might ask: what to do if input matches more then one pattern (is 02-01-2012 2nd of January or February the 1st?) Well, then you have bigger issues...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top