Java:校验日期格式(支持闰年、大小月)的三种方法

程序支持校验标准yyyyMMdd日期格式,支持平年闰年29日、大小月的31日的校验

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CheckDateFormat {

	/**
	 * @param args
	 * @throws ParseException 
	 */
	public static void main(String[] args) throws ParseException {
			String str="20210229";
			System.out.println(isValidDate1(str));//612
			System.out.println(isValidDate2(str));//804
			System.out.println(isValidDate3(str));//259
	}	 

	/**
	 * 方法一:判断字符串是否为日期格式,利用日期类DateFormat类parse方法校验
	 */
	public static boolean isValidDate1(String inDate){
		if(inDate==null){
			return false;
		}
		SimpleDateFormat dataFormat = new SimpleDateFormat("yyyyMMdd");//或yyyy-MM-dd
		
		if(inDate.trim().length() != dataFormat.toPattern().length()){
			return false;
		}
		dataFormat.setLenient(false);//该方法用于设置Calendar严格解析字符串;默认为true,宽松解析
		
		try {
			dataFormat.parse(inDate.trim());
		} catch (ParseException e) {
			return false;
		}
		
		return true;
	}
	/** 
	* 方法二:判断字符串是否为日期格式,利用正则表达式方法校验
	*/ 
	public static boolean isValidDate2(String strDate) { 
		Pattern pattern = Pattern .compile("^((\\d{2}(([02468][048])|([13579][26]))[\\-\\/\\s]?"
				+ "((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(3[01])))|(((0?"
				+ "[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|(0?2[\\-\\/\\s]?((0?"
				+ "[1-9])|([1-2][0-9])))))|(\\d{2}(([02468][1235679])|([13579][01345789]))"
				+ "[\\-\\/\\s]?((((0?[13578])|(1[02]))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|"
				+ "(3[01])))|(((0?[469])|(11))[\\-\\/\\s]?((0?[1-9])|([1-2][0-9])|(30)))|"
				+ "(0?2[\\-\\/\\s]?((0?[1-9])|(1[0-9])|(2[0-8]))))))(\\s(((0?[0-9])|([1-2]"
				+ "[0-3]))\\:([0-5]?[0-9])((\\s)|(\\:([0-5]?[0-9])))))?$");   
		Matcher m = pattern.matcher(strDate); 
		
		return (m.matches())?true:false;
	} 
	/**
	 * 方法三:判断字符串是否为日期格式,利用日期组合规则校验
	 */
	public static boolean isValidDate3(String inDate){
		int year = Integer.parseInt(inDate.substring(0,4));//年份
		int month = Integer.parseInt(inDate.substring(4,6));//月份
		int day = Integer.parseInt(inDate.substring(6,8));//天数
		if (month < 1 || month > 12) {//校验月份格式
			return false;
		}
		if (day < 1 || day > 31) {//校验天数格式
			return false;
		}
		if ((month == 4 || month == 6 || month == 9 || month == 11) &&(day == 31)) {//是否不符合4月、6月、9月、11月最大天数30日
			return false;
		}
		boolean leap=false;
		if (month == 2) {//闰年2月为29天,平年2月为28天
			leap = (year % 4 == 0 &&(year % 100 != 0 || year % 400 == 0));
			if (day>29 || (day == 29 && !leap)) {
				return false;
			}
		}
		return true;
	}
}

 

  • 1
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值