SimpleDateFormat方法解析中的可能错误 [英] SimpleDateFormat possible error in method parse
问题描述
我收到一个表示日期的字符串,我需要将此字符串转换为日期,并验证该字符串是有效日期。
我收到字符串33 -12-2013分析方法返回日期01-01-2014,代码:
日期fechaVencimientoFormateada;
SimpleDateFormat formateador = new SimpleDateFormat(dd-MM-yyyy);
try
{
fechaVencimientoFormateada = formateador.parse(33-12-2013);
System.out.println(formateador.format(fechaVencimientoFormateada));
}
catch(ParseException e)
{
System.out.println(ERROR!);
}
输出:
Thu Jan 02 00:00:00 COT 2014年
我预计有一个ParseException,任何想法?
其他示例:
字符串日期:365-12-2013
输出:Sun Nov 30 00:00:00 COT 2014
字符串日期:1-24-2013
输出:Mon Dec 01 00:00:00 COT 2014
为什么ParseException不会抛出?
$ b $确定你的 setLenient(false)
在 SimpleDateFormat
。否则,它将解析大量的无效日期,无一例外,您不能相信输出太多。 I receive a string that represent a date, I need convert this string to date, and validate that the string is a valid date.
I receive the string 33-12-2013 a the parse method return a date 01-01-2014, the code:
Date fechaVencimientoFormateada;
SimpleDateFormat formateador = new SimpleDateFormat( "dd-MM-yyyy" );
try
{
fechaVencimientoFormateada = formateador.parse( "33-12-2013" );
System.out.println( formateador.format(fechaVencimientoFormateada) );
}
catch ( ParseException e )
{
System.out.println("ERROR!");
}
the output: Thu Jan 02 00:00:00 COT 2014
and I expected a ParseException, any idea?
And other examples:
String date: 365-12-2013 output: Sun Nov 30 00:00:00 COT 2014
String date: 1-24-2013 output: Mon Dec 01 00:00:00 COT 2014
why ParseException is not throwing?
Make sure you setLenient(false)
on the SimpleDateFormat
. Otherwise it will parse lots of invalid dates without exception and you can't trust the output too much.
这篇关于SimpleDateFormat方法解析中的可能错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!