Java SimpleDateFormat返回意外结果 [英] Java SimpleDateFormat returns unexpected result

查看:80
本文介绍了Java SimpleDateFormat返回意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用Java的SimpleDateFormat来解析使用以下代码的String。

I'm trying to use SimpleDateFormat of Java to parse a String to date with the following code.

public class DateTester {

    public static void main(String[] args) throws ParseException {
        String dateString = "2011-02-28";

        SimpleDateFormat dateFormat = new SimpleDateFormat("MM-dd-yyyy");

        System.out.println(dateFormat.parse(dateString));
    }
}

我原本期待一些解析错误。但有趣的是,它会打印以下字符串。

I was expecting some parse error. But interestingly, it prints the following String.

Wed Jul 02 00:00:00 IST 195

无法推断出来。任何人都可以帮忙吗?

Couldn't reason it out. Can anyone help?

谢谢

推荐答案

SimpleDateFormat 已将 2011 解析为编号2011,因为月份( MM )是日期模式的第一部分。

SimpleDateFormat has parsed 2011 as month number 2011, because month (MM) is the first part of the date pattern.

如果你将2011年增加到第28年,你将获得195年。

If you add 2011 months to year 28, you get year 195.

2011个月是167年零7个月。七月是第七个月。您将02指定为日,28指定为年,28 + 167 = 195,因此 02年7月2日是正确的。

2011 months is 167 years and 7 months. July is the 7th month. You specified 02 as the day, 28 as the year, 28 + 167 = 195, so 02 July 195 is correct.

这篇关于Java SimpleDateFormat返回意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆