简体   繁体   English

在 Java 中使用日期的意外行为

[英]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 .您想要的数据与SimpleDateFormat指定的格式不匹配。 However, by default, it is lenient in how it parses the data.但是,默认情况下,它解析数据的方式是宽松的。 For example, September 31st would be interpreted as October 1st.例如,9 月 31 日将被解释为 10 月 1 日。

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.在这里,它被解释为 23 年的 2,015 月的第 9 天。2,015 个月是 167 年零 11 个月,当加上 23 年产生 190 年。在这种情况下,它是非常宽松的。

The output format is what is expected when printing out a Date directly.输出格式是直接打印Date时的预期格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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