日期字符串解析--SimpleDateFormat严格限制日期转换setLenient(false)

输入“33/12/2011”,用SimpleDateFormat parse()方法,转化为Date(2012,01,02).这样处理相当“33/12/2011”是正常输入,如果需要"33/12/2011”报错,即把"33/12/2011"当作错误格式,刚开始自己写了段逻辑判断:

把转成的日期再反转回来,再比较是否一致,即使用format方法再转换成字符串,和传入的那个串作比较,如果不相等,则证明传入的那个日期格式是错误的

Java代码  收藏代码
  1. private String getDestDateStrFromSrcDateStr(String dateStr,  
  2.         String srcDateFormat, String descDateFormat)  
  3. {  
  4.     try  
  5.     {  
  6.         final SimpleDateFormat src_sdf = new SimpleDateFormat(srcDateFormat);  
  7.         final Date date = src_sdf.parse(dateStr);  
  8.           
  9.         //把转成的日期再反转回来,再比较是否一致  
  10.         if (srcDateFormat.length() != dateStr.length()  
  11.                 || !dateStr.equals(src_sdf.format(date)))  
  12.         {  
  13.             LOGGER.error("the src date format is {} , but input the date string value is {}, input illegal",  
  14.                     srcDateFormat,  
  15.                     dateStr);  
  16.             throw new ParseMessageException(  
  17.                     ErrorKeys.PAYMENT_AG_CONFIG_SERVICE_PARAM_VALIDATE_FAILED);  
  18.         }  
  19.           
  20.         //把转成的date类型转换为目标格式日期字符串(yyyyMMdd)  
  21.         final SimpleDateFormat dest_sdf = new SimpleDateFormat(  
  22.                 descDateFormat);  
  23.         LOGGER.info("the converted dest date str:{}"  
  24.                 + dest_sdf.format(date));  
  25.         return dest_sdf.format(date);  
  26.     }  
  27.     catch (java.text.ParseException e)  
  28.     {  
  29.         LOGGER.error("the src date format is {} , but input the date string value is {}, input illegal",  
  30.                 srcDateFormat,  
  31.                 dateStr);  
  32.         throw new ParseMessageException(  
  33.                 ErrorKeys.PAYMENT_AG_CONFIG_SERVICE_PARAM_VALIDATE_FAILED);  
  34.     }  
  35. }  

 总觉得这种方法显得很笨拙,后来找找API,发现有一个方法:setLenient(false)可以直接使用。哎~何必费这么大劲呢

测试方法:

Java代码  收藏代码
  1. import java.text.DateFormat;  
  2. import java.text.ParseException;  
  3. import java.text.SimpleDateFormat;  
  4. import java.util.Date;  
  5.   
  6.   
  7. public class DateTest {  
  8.     public static void main(String[] args) throws ParseException {  
  9.         DateFormat format = new SimpleDateFormat("dd/MM/yyyy");  
  10.         format.setLenient(false);  
  11.         Date date = format.parse("33/12/2011");  
  12.         System.out.println(date);  
  13.     }  
  14. }  

该方法的作用:

setLenient用于设置Calendar是否宽松解析字符串,如果为false,则严格解析;默认为true,宽松解析

原文地址:https://www.cnblogs.com/exmyth/p/7838981.html