简体   繁体   中英

Unexpected Behavior using Dates in Java

I have the following code:

import java.util.Date;
import java.util.Calendar;
import java.text.SimpleDateFormat;

import org.junit.Test;

public class DateCalendarTest  {     
    @Test
    public void test1() {
        private final DateFormat df1 = new SimpleDateFormat("MM/dd/yyyy");    
        String batchdt = "2015/09/23";
        System.out.println("Date & Calendar Test: " + batchdt);
        Calendar cal = Calendar.getInstance();
        Date date1 = df1.parse(batchdt);
        cal.setTime(date1);
        System.out.println("Date & Calendar Test: " + cal.getTime());
    }
}

Output:

Date Calendar Test: 2015/09/23
Date Calendar Test: Mon Nov 09 00:00:00 EST 190

Can someone please explain why this behaves in this manner?

Your intended data doesn't match the format specified in your SimpleDateFormat . However, by default, it is lenient in how it parses the data. For example, September 31st would be interpreted as October 1st.

Here, it's interpreted as day 9 of month 2,015 of year 23. 2,015 months is 167 years, 11 months, which when added to the year 23 yields the year 190. In this case, it is very lenient.

The output format is what is expected when printing out a Date directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM