
正文
java正则判断生日代码 java正则表达式校验日期
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
java如何对生日(yyyymmdd)进行合法性判断?
修改你说的存在的bug
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class TestBirthday {
public static void main(String[] args){
String birthday="20130132";
System.out.println(isBirthday(birthday));
}
/*
* @param : birthday 传入一个日期格式的字符串
* 支持 yyyy-MM-dd ,yyyyMMdd MM-dd-yyyy ,yyyy年MM月dd日
* @isBirthday 判断输入的字符串是否是合法的生日 生日不能大于当前日期
* */
public static boolean isBirthday(String birthday){
//定义需要过滤的条件,可以将你期望的日期格式添加到数组中
String[] formats={
"yyyy-MM-dd",
"yyyyMMdd",
"MM-dd-yyyy",
"yyyy年MM月dd日"
};
/*
* 设置格式过滤器
*/
//记录传入的日期字符串,转换成日期类型
Date birth=null;
//判断格式是否正确,默认值为false
boolean isRight=false;
for(String f:formats){
try {
birth =new SimpleDateFormat(f).parse(birthday);
//校验日期转换后是和传入的值不相同,说明日期传入有问题
//修正楼上提到的bug
if(!new SimpleDateFormat(f).format(birth).equals(birthday)){
return false;
}
isRight=true;
break;
} catch (ParseException e) {}
}
if(isRight){
//获取当前日期的毫秒数
long now =new Date().getTime();
//获取生日的毫秒数
long birthTime = birth.getTime();
//如果当前时间小于生日,生日不合法。反之合法
return birthTime=now;
}else{
//输入的参数类型不是日期类型,或者类型和过滤中设置的类型不匹配
return false;
}
}
}
相关问答
Q1: 用JAVA编程,输入自己的生日,判断自己生日是当年中的第几天和星期几。
import java.io.*;
import java.util.*;
public class GetBirth {
int year = 0;
int month = 0;
int day = 0;
Calendar cld = Calendar.getInstance();//创建一个日历
public GetBirth(){
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.println("请输入年、月、日java正则判断生日代码:");
try {
year = Integer.parseInt(in.readLine());
month = Integer.parseInt(in.readLine());
day = Integer.parseInt(in.readLine());
} catch (NumberFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
//将日历时间设置成生日那天
public void setDate(int year,int month,int day){
cld.set(year,month-1,day);
}
//获取该日是一年当中java正则判断生日代码的第几天
public int getDay(){
return cld.get(6);
}
//获取该日是星期几
public String getDate(){
int date = cld.get(7);
return getWeekday(date);
}
//判断解析一周7天java正则判断生日代码的值
public String getWeekday(int dayofweek){
switch(dayofweek){
case 1: return "星期日";
case 2: return "星期一";
case 3: return "星期二";
case 4: return "星期三";
case 5: return "星期四";
case 6: return "星期五";
case 7: return "星期六";
default:return "error";
}
}
public static void main(String[] args) {
GetBirth gb = new GetBirth();
gb.setDate(gb.year, gb.month, gb.day);
System.out.println(gb.getDay());
System.out.println(gb.getDate());
}
}
希望对楼主有所帮助java正则判断生日代码,谢谢。
Q2: 编写java主类,运用正则表达式,验证出生日期的合法性,求大神帮帮忙解决
如果出生日期是这种形式: 1990/01/01
String regex = "^\\d{4}/\\d{2}\\d{2}";
String birthdate="1993/02/03";
Boolean result= birthdate.matches(regex );
关于java正则判断生日代码和java正则表达式校验日期的介绍到此就结束了,不知道你从中找到你需要的信息了吗 ?如果你还想了解更多这方面的信息,记得收藏关注本站。








