[英]Date format conversion not working as expected in Java
this is a well known question already appeared on stackoverflow. 这是已经在stackoverflow上出现的一个众所周知的问题。 I have been asked to solve a bug in a web application.
我被要求解决Web应用程序中的错误。 I have a date coming from a web form, the user is supposed to enter a valid date in a given format
dd/MM/yyyy
. 我有一个来自网络表单的日期,用户应该以给定格式
dd/MM/yyyy
输入有效日期。
The application is using Struts 1.3 as a framework, and this is what I found in validate method of the corresponding FormBean. 该应用程序使用Struts 1.3作为框架,这是我在相应FormBean的validate方法中发现的。
DateFormat dateFormat = new SimpleDateFormat( "dd/MM/yyyy", aLocale );
try{
mydate = dateFormat.parse( formDate );
}
catch( ParseException pe ){
errors.add( "error", new ActionError( "error.date.invalid" ) );
}
However it's happening that the error is not raised for example when user enter year in short format, ie 01/10/12
, which is converted into a date, looking in database I found 01/10/0012
. 但是它的发生的错误不会引发例如,当用户在短格式输入,即每年
01/10/12
,将其转化为一个日期,寻找数据库中,我发现01/10/0012
。
As a quick fix I tried to use setLenient(false)
, but the exception is still not raised, and mydate still results in a valid but wrong date. 作为快速解决方案,我尝试使用
setLenient(false)
,但是仍然不会引发异常,并且mydate仍然会导致有效但错误的日期。
Before going to mess with regex and string pre parsing, I was wondering if I am missing something. 在搞砸正则表达式和字符串预解析之前,我想知道是否丢失了一些东西。 Especially when locale is used within date format instantiation.
特别是在日期格式实例化中使用语言环境时。
Current Jdk used in project is 1.5 当前在项目中使用的Jdk为1.5
You can use format pattern like: 您可以使用如下格式格式:
DateFormat dateFormat = new SimpleDateFormat( "dd/MM/yy", aLocale );
So it will convert "01/11/12" to Jan 11, 2012 and "01/11/86" to Jan 11, 1986 因此它将“ 01/11/12”转换为2012年1月11日,并将“ 01/11/86”转换为1986年1月11日
if Year is in "yyyy" format than the year is interpreted literally, regardless of the number of digits. 如果Year为“ yyyy”格式,则无论数字位数如何,年份都将按字面意义进行解释。
For more details read : http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html#year 有关更多详细信息,请阅读: http : //docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html#year
Or you can handle User input in javascript/Java code for "dd/mm/yyyy" format. 或者,您也可以使用javascript / Java代码以“ dd / mm / yyyy”格式处理用户输入。 Resctrict user to enter date in "dd/mm/yyyy" format only.
限制用户仅以“ dd / mm / yyyy”格式输入日期。
The problem is that 01/10/12
does satisfy dd/MM/yyyy
. 问题在于,
01/10/12
dd/MM/yyyy
01/10/12
确实满足dd/MM/yyyy
。 It's just that it (as you've discovered) refers to 12 AD. 只是(您已经发现)它指的是12 AD。
Your options are : 您的选择是:
My vote would be for a combination of 1 and 3. 1 for the case where JavaScript is enabled and 3 to handle the rare instances where JS validation fails. 我的投票将是1和3的组合。1表示启用JavaScript的情况,3表示处理JS验证失败的罕见情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.