为什么Java的SimpleDateFormat会解析这个问题 [英] Why Does Java's SimpleDateFormat parse this

查看:258
本文介绍了为什么Java的SimpleDateFormat会解析这个问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我有一个简单的日期格式设置自定义格式字符串:
MMddyy

Hi I've got a simple date format set up with a custom format string: MMddyy

我给它以下值来解析:
4 1 01

and I give it the following value to parse: 4 1 01

我不认为它应该解析这个因为空格但简单日期格式返回日期

I don't think it should parse this because of the spaces but the Simple Date Format is returning the date

4月4日0001AD

April 4th 0001AD

任何想法为什么?

推荐答案

这是预期的行为 - 你告诉DateFormat对象期望一个6字符的字符串表示日期,这是你传入的。空格被解析好。但是,如果您使用4x1x01,则会出错。请注意,在解析时,leniency默认为true,例如。

This is expected behaviour - you are telling the DateFormat object to expect a 6 character String representation of a date and that is what you passed in. Spaces are parsed OK. However, if you used "4x1x01" you would get an error. Note that when parsing, leniency defaults to true e.g.

DateFormat df = new SimpleDateFormat("MMddyy");
Date date = df.parse("4 1 01"); // runs successfully (as you know)

DateFormat df = new SimpleDateFormat("MMddyy");
Date date = df.parse("41 01"); // 5 character String - runs successfully

DateFormat df = new SimpleDateFormat("MMddyy");
df.setLenient(false);
Date date = df.parse("41 01"); // 5 character String - causes exception

DateFormat df = new SimpleDateFormat("MMddyy");
Date date = df.parse("999999"); // 6 character String - runs successfully

DateFormat df = new SimpleDateFormat("MMddyy");
df.setLenient(false);
Date date = df.parse("999999"); // 6 character String - causes exception

当leniency设置为true(默认行为)时,解析努力破译无效输入,例如31个月的第35天成为下个月的第4天。

When leniency is set to true (the default behaviour), the parse makes an effort to decipher invalid input e.g. the 35th day of a 31 day month becomes the 4th day of the next month.

这篇关于为什么Java的SimpleDateFormat会解析这个问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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