Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 846
David S. Avatar asked Jan 18 '26 14:01

David S.


2 Answers

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.

like image 192
Sergey Kalinichenko Avatar answered Jan 21 '26 04:01

Sergey Kalinichenko


How to avoid this?

Use a better date-time library.

That means either:

  • Joda-Time
  • The java.time package
    • Bundled with Java 8
    • Inspired by Joda-Time but re-architected
    • Defined by JSR 310

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]
like image 39
Basil Bourque Avatar answered Jan 21 '26 04:01

Basil Bourque



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!