1

I am trying to validate dates using simple data format and it parses strange dates.

 val dateFormat = new SimpleDateFormat("dd MMM, yyyy")
      dateFormat.setLenient(false)
      dateFormat.parse("01 Jan, 2k11")

Sun Jan 01 00:00:00 IST 2

fast time : -62104253400000

cDate : C.E. 2-01-01T00:00:00.000+0530

Ole V.V.
  • 81,772
  • 15
  • 137
  • 161
H.Aadhithya
  • 205
  • 1
  • 12
  • I recommend you don’t use `SimpleDateFormat`. That class is notoriously troublesome and long outdated. Instead use `DateTimeFormatter` and other classes from [java.time, the modern Java date and time API](https://docs.oracle.com/javase/tutorial/datetime/). Also they won’t show the bad behaviour you’ve observed with `SimpleDateFormat`. – Ole V.V. Jul 12 '19 at 11:07

1 Answers1

1

I started digging through the source code for SimpleDateFormat, and read enough to glean what appears to be happening here. What is happening is that your year component 2k11 is being interpreted as a two digit year (actually one digit, 2), and everything that follows is being ignored as not being part of the date pattern. Consider the following code which produces the same result:

  DateFormat dateFormat = new SimpleDateFormat("dd MMM, yyyy");
  dateFormat.setLenient(false);
  Date blah = dateFormat.parse("01 Jan, 2 Jon Skeet");
  System.out.println(blah);

This prints:

Sun Jan 01 00:00:00 CET 2

As you can see, the intepreted year is 2, and the Jon Skeet blurb was ignored. To understand exactly why SimpleDateFormat is doing this, read the source code.

Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
  • Rather than the source code I recommend [the documentation](https://docs.oracle.com/javase/9/docs/api/java/text/DateFormat.html#parse-java.lang.String-). `parse` is declared in the superclass, `DateFormat`, and it “Parses text from the beginning of the given string to produce a date. The method may not use the entire text of the given string.” – Ole V.V. Jul 12 '19 at 11:11
  • @OleV.V. That helps too :-) ... I figured this was a quirk which the Javadoc conveniently would not mention. – Tim Biegeleisen Jul 12 '19 at 11:11
  • I agree that the `SimpleDateFormat` documentation is not always complete, so I understand your *a priori* suspicion. – Ole V.V. Jul 12 '19 at 11:12