DateFormat给出了错误的答案

Res*_*hmi 4 java date

我使用以下代码格式化日期.但是当我以错误的格式提供数据时,它会给出意想不到的结果.

DateFormat inputFormat = new SimpleDateFormat("yyyy/MM/dd");
DateFormat outputFormat = new SimpleDateFormat("yyyy-MM-dd");`

String dateVal = "3/8/2016 12:00:00 AM";

try {
    Date date = inputFormat.parse(dateVal);
    String formattedVal = outputFormat.format(date);
    System.out.println("formattedVal : "+formattedVal);
} catch (ParseException pe) {
    throw pe;
}
Run Code Online (Sandbox Code Playgroud)

在上面的例子中,输出是 - formattedVal:0009-02-05.

它不是抛出Parse异常,而是解析值并给出错误的输出.有人可以帮我理解这种异常行为.

Xvo*_*lks 7

日期解析器尽最大努力将给定的字符串解析为日期.

这里3/8/2016用格式年/月/日解析,所以:

  • 年= 3
  • 月= 8 - > 8个月是0.667年
  • 日= 2016年 - > 2016年是〜5.5年

所以年= 3 + 5.5 = 8.5 + 0.667 = 9.17.这给了09年2月5日.