日期字符串解析-SimpleDateFormat严厉限制日期转换setLenient(false)
日期字符串解析--SimpleDateFormat严格限制日期转换setLenient(false)
输入“33/12/2011”,用SimpleDateFormat parse()方法,转化为Date(2012,01,02).这样处理相当“33/12/2011”是正常输入,如果需要"33/12/2011”报错,即把"33/12/2011"当作错误格式,刚开始自己写了段逻辑判断:
把转成的日期再反转回来,再比较是否一致,即使用format方法再转换成字符串,和传入的那个串作比较,如果不相等,则证明传入的那个日期格式是错误的
private String getDestDateStrFromSrcDateStr(String dateStr, String srcDateFormat, String descDateFormat) { try { final SimpleDateFormat src_sdf = new SimpleDateFormat(srcDateFormat); final Date date = src_sdf.parse(dateStr); //把转成的日期再反转回来,再比较是否一致 if (srcDateFormat.length() != dateStr.length() || !dateStr.equals(src_sdf.format(date))) { LOGGER.error("the src date format is {} , but input the date string value is {}, input illegal", srcDateFormat, dateStr); throw new ParseMessageException( ErrorKeys.PAYMENT_AG_CONFIG_SERVICE_PARAM_VALIDATE_FAILED); } //把转成的date类型转换为目标格式日期字符串(yyyyMMdd) final SimpleDateFormat dest_sdf = new SimpleDateFormat( descDateFormat); LOGGER.info("the converted dest date str:{}" + dest_sdf.format(date)); return dest_sdf.format(date); } catch (java.text.ParseException e) { LOGGER.error("the src date format is {} , but input the date string value is {}, input illegal", srcDateFormat, dateStr); throw new ParseMessageException( ErrorKeys.PAYMENT_AG_CONFIG_SERVICE_PARAM_VALIDATE_FAILED); } }
总觉得这种方法显得很笨拙,后来找找API,发现有一个方法:setLenient(false)可以直接使用。哎~何必费这么大劲呢
测试方法:
import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; public class DateTest { public static void main(String[] args) throws ParseException { DateFormat format = new SimpleDateFormat("dd/MM/yyyy"); format.setLenient(false); Date date = format.parse("33/12/2011"); System.out.println(date); } }
该方法的作用:
setLenient用于设置Calendar是否宽松解析字符串,如果为false,则严格解析;默认为true,宽松解析