Java中实现日期合法性判断
日期是我们平常生活中必不可少的一部份。在Java中,常常需要对日期进行操作,比如判断日期会不会合法。本文将针对Java中日期合法性判断进行论述,并介绍怎么实现。
判断日期会不会合法的方法
在Java中,判断日期会不会合法的方法主要有以下几种:
使用SimpleDateFormat类判断日期会不会合法
SimpleDateFormat类是Java中用来格式化日期的一个类,我们可以通过它的parse()方法将字符串转换成Date类型,并捕获异常来判断日期会不会合法。代码示例:
publicstaticbooleanisValidDate(StringdateStr){DateFormatformatter=newSimpleDateFormat(yyyy-MM-dd);formatter.setLenient(false);try{Datedate=formatter.parse(dateStr);returntrue;}catch(ParseExceptione){returnfalse;}}使用Calendar类判断日期会不会合法
Calendar类是Java中用来获得和设置日期时间字段的一个抽象类,通过调用setLenient()方法来设置日期格式会不会宽容,然后通过set()方法设置年月日等日期字段值,最后调用getTime()方法返回一个Date类型的对象,如果在转换进程中发现不符合格式的字符将会抛出异常。代码示例:
publicstaticbooleanisValidDate(StringdateStr){try{DateFormatformatter=newSimpleDateFormat(yyyy-MM-dd);formatter.setLenient(false);Datedate=formatter.parse(dateStr);Calendarcal=Calendar.getInstance();cal.setTime(date);intyear=cal.get(Calendar.YEAR);intmonth=cal.get(Calendar.MONTH)+1;intday=cal.get(Calendar.DATE);if(year>0&&month>0&&month<=12&&day>0&&day<=31){returntrue;}else{returnfalse;}}catch(Exceptione){returnfalse;}}使用正则表达式判断日期会不会合法
正则表达式也能够用来判断日期会不会合法,一般使用字符串匹配的方式来实现。Pattern和Matcher类可以用来实现正则表达式匹配。代码示例:
publicstaticbooleanisValidDate(StringdateStr){Stringpattern=^\d{4}-\d{1,2}-\d{1,2}$;Patternr=Pattern.compile(pattern);Matcherm=r.matcher(dateStr);if(m.matches()){String[]dateArray=dateStr.split(-);intyear=Integer.parseInt(dateArray[0]);intmonth=Integer.parseInt(dateArray[1]);intday=Integer.parseInt(dateArray[2]);if(year>0&&month>0&&month<=12&&day>0&&day<=31){returntrue;}else{returnfalse;}}else{returnfalse;}}结语
对日期进行合法性判断在Java开发中是一个常见的需求。本文介绍了Java中经常使用的几种判断日期会不会合法的方法,并提供了相关的代码示例。在实际开发中,可以根据具体需求选择适合的方法进行实现。
桂|哥|网|络www.guIgege.cn
TOP