导航:首页 > 编程语言 > java日期验证

java日期验证

发布时间:2023-06-10 08:54:35

1. java判断是否是日期

楼主提出的问题有点片面,我的理解是,你是不是想判断字符串是不是日期格式?如果已经是日期类型,那就不需要判断了,对把。判断给定字符串是不是日期我给你提供两种解决思路,一种是用正则,代码我给你写好了。

publicbooleanisDate(Stringdate){
/**
*判断日期格式和范围
*/
Stringrexp="^((\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]))))))";

Patternpat=Pattern.compile(rexp);

Matchermat=pat.matcher(date);

booleandateType=mat.matches();

returndateType;
}

参数就是你要判断的日期字符串,返回布尔值;

另一种方式就是:玩字符串正则才是王道嘛!希望采纳

publicbooleanisValidDate(Stringstr){
booleanconvertSuccess=true;
//指定日期格式为四位年/两位月份/两位日期,注意yyyy/MM/dd区分大小写;
//如果想判断格式为yyyy-MM-dd,需要写成-分隔符的形式
SimpleDateFormatformat=newSimpleDateFormat("yyyy/MM/ddHH:mm");
try{

format.setLenient(false);
format.parse(str);
}catch(ParseExceptione){
//e.printStackTrace();
//如果抛出ParseException或者NullPointerException,就说明格式不对
convertSuccess=false;
}
returnconvertSuccess;
}

推荐使用正则,

2. Java里面效验日期的正则表达式

publicstaticvoidmain(String[]args)
{
StringcheckValue="20000431112230";
Stringyear=checkValue.substring(0,4);//获取年份
Stringmonth=checkValue.substring(4,6);//获取月份
BooleanisLeap=leapYear(Integer.parseInt(year));//判断闰年
System.out.println(isLeap);
StringBuffereL=newStringBuffer();
StringlongMonth="01030507081012";//31天的月份
Stringfix="([2][0-3]|[0-1][0-9]|[1-9])[0-5][0-9]([0-5][0-9]|[6][0])";


if(isLeap&&month.equals("02")){//针对2月份的情况【闰年】
eL.append("\d{4}([1][0-2]|[0][0-9])([2][0-1]|[1-2][0-9]|[0][1-9]|[1-9])"+fix);
}elseif(!isLeap&&month.equals("02")){//针对2月份的情况【非闰年】
eL.append("\d{4}([1][0-2]|[0][0-9])([2][0-1]|[1-2][0-8]|[0][1-9]|[1-9])"+fix);
}elseif(longMonth.contains(month)){//31天月份
eL.append("\d{4}([1][0-2]|[0][0-9])([3][0-1]|[1-2][0-9]|[0][1-9]|[1-9])"+fix);
}else{//30天月份
eL.append("\d{4}([1][0-2]|[0][0-9])([3][0]|[1-2][0-9]|[0][1-9]|[1-9])"+fix);
}
Patternp=Pattern.compile(eL.toString());
Matcherm=p.matcher(checkValue);
booleanflag=m.matches();
if(flag)
{
System.out.println("格式正确");
}
else
{
System.out.println("格式错误");
}

}
publicstaticbooleanleapYear(intyear){
BooleanisLeap=false;
if(((year%100==0)&&(year%400==0))
||((year%100!=0)&&(year%4==0)))
isLeap=true;
returnisLeap;
}

阅读全文

与java日期验证相关的资料

热点内容
什么是适合自己的app 浏览:451
云服务器怎么补漏洞 浏览:176
如何看自己的安卓是什么等级 浏览:633
被丁磊挖走的程序员 浏览:19
gsk980ta编程 浏览:507
单片机离线 浏览:84
解压助眠敲击外国长指甲 浏览:421
3次元编程 浏览:803
夫妻传送英文命令 浏览:316
程序员题代做 浏览:950
戴尔服务器怎么扩大内存 浏览:641
解压包密码消失 浏览:135
昆仑通态触摸屏用户窗加密 浏览:564
农信app怎么看日额 浏览:865
iphone备忘录包含视频无法加密 浏览:283
抖音快手红包源码 浏览:137
程序员资源分析 浏览:586
linux交换分区大小 浏览:922
mt怎么编译 浏览:337
qq邮箱打开pdf 浏览:461