2
public static void main(String[] args) throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); 
    String dateStr = "35/35/1985";
    Date date = sdf.parse(dateStr);

i was expecting run time exception like date parse exception but returned date object is Sat Dec 05 00:00:00 IST 1987

By what logic string 35/35/1985 parsed to date Sat Dec 05 00:00:00 IST 1987?

update:- If I set the setLenient(false), it throws exception. But if I make it true By what logic string 35/35/1985 parsed to date Sat Dec 05 00:00:00 IST 1987?

emilly
  • 10,060
  • 33
  • 97
  • 172
  • 3
    http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#setLenient%28boolean%29 –  Feb 04 '16 at 12:28

3 Answers3

5
public static void main(String[] args) throws ParseException {
    SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy"); 
    String dateStr = "35/35/1985";
    Date date = sdf.parse(dateStr);

To answer your "logic behind" question: Well, it will be parsed as

xx.xx.1985
-> set / add 35 Months (xx.35.1982 -> xx.11.1987)
-> set / add 35 Days (35.11.1987 -> 05.12.1987)

If you don't want this behaviuor, set lenient to false: http://docs.oracle.com/javase/7/docs/api/java/text/DateFormat.html#setLenient%28boolean%29

CaptJak
  • 3,592
  • 1
  • 29
  • 50
Jörn Buitink
  • 2,906
  • 2
  • 22
  • 33
1

To keep track of time, Java counts the number of milliseconds from the start of January 1, 1970. This means, for example, that January 2, 1970, began 86,400,000 milliseconds later. (...) The Java Date class keeps track of those milliseconds as a long value. Because long is a signed number, dates can be expressed before and after the start of January 1, 1970.

From JavaWorld.com

Basically, Java's engine does not know what a Date is, so a date is nothing but a reference to how many milliseconds have passed since the "Beginning" and it will then be converted to a nice MM/DD/YYYY format. Same thing in the other direction. So technically, 35/35/1985 is not a mistake, it simply means "substract 34 months, 34 days and 1985 years to 0 months, 0 days and 1970 years".

This can be useful if you are calculating Loans for example where people tend to reference 5 years as "60 months". See the point?

AceShot
  • 350
  • 3
  • 10
0

In you above code

you mentioned

year => 1985
month=> 35
day =>35

now first, year is 1985. if month is 12 then it will be 1985 after that when month is 24 it will be 1986. above 24, year will be 1987 and for month 35 it is Nov 1987. now your date is 35 which is above 30 so it will go to December 5 with adding one year i.e 1987.

so finally Dec 5 1987.

Musaddique S
  • 1,539
  • 2
  • 15
  • 36