Aakash
Aakash

Reputation: 1791

Date parsing gone wrong

Working on an application which saves a date for a particular course i.e. the end date for every course that gets created.

This service accepts the date in MM/dd/yyyy format.

For example,

course = {
    "courseName": "My Course",
    "endDate": "01/10/2015"
}

Which should get parsed as "01/10/2015" i.e. "10 Jan 2015" in the service.

But, there were instances where the date was received in the wrong format, i.e dd/MM/yyyy

course = {
    "courseName": "My Course",
    "endDate": "13/01/2015"
}

Which got parsed as "01/01/2016" i.e. "01 Jan 2016".

The above parsing is done using

String d = "13/01/2015";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
Date date = format.parse(d);

My question is, is there are way I can get back the original date by reversing the wrongly parsed date?

I tried to parsing it using pattern "dd/MM/yyyy", but I got "01/01/2016".

Upvotes: 0

Views: 368

Answers (1)

George Lee
George Lee

Reputation: 826

The problem is, once you have the parsed value "01/01/2016", how do you know whether that the original value was actually "01/01/2016" or your incorrect "13/01/2015". You don't.

All I can suggest is for future reference is that you setLenient(false) then the SimpleDateFormat will throw an appropriate ParseException when it encounters something like this.

String d = "13/01/2015";
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
format.setLenient(false)
Date date = format.parse(d); // throws ParseException

Upvotes: 3

Related Questions