David S.
David S.

Reputation: 11200

'3-50-2014' is '3-2-2018' for Java?

I was trying to use the SimpleDateFormat to parse some date string, and I notice this ridiculous incident.

SimpleDateFormat sdf = new SimpleDateFormat("d-M-yyyy");
Date d = sdf.parse("3-50-2014");

Instead of giving me an error, it returns '3-2-2018' normally...How could this happen? How to avoid this?

Upvotes: 2

Views: 76

Answers (2)

Basil Bourque
Basil Bourque

Reputation: 339858

How to avoid this?

Use a better date-time library.

That means either:

Joda-Time

Using Joda-Time 2.4.

DateTimeFormatter formatter = DateTimeFormat.forPattern( "d-M-yyyy" );
DateTime dateTime = formatter.parseDateTime( "3-50-2014" ); // Note the invalid month number.

When run, we get an Exception thrown (as expected).

Exception in thread "main" org.joda.time.IllegalFieldValueException: Cannot parse "3-50-2014": Value 50 for monthOfYear must be in the range [1,12]

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726967

This is because the SimpleDateFormat is in lenient mode: it forgives "small" issues, such as setting the months too high, adjusting the year instead. For example, in your case it interprets the additional 48 months as four years.

Calling sdf.setLenient(false) will fix this problem.

Demo.

Upvotes: 13

Related Questions