题目:通过控制台输入两个时间字符串,第一个格式如2015-01-02,第二个的格式如2009年09月09日,用正则表达式进行格式校验,再判断哪个时间在前,哪个在后,并计算输出两个日期之间相差多天
public class Exercise02 {
public static void main(String[] args) {
getDate();
}
public static void getDate(){
Scanner scan = new Scanner(System.in);
String regex = "\\d{4}(-\\d{2}){2}";
//判断格式是否正确
String str1 = "";
while(true){
System.out.println("输入第一个日期:");
str1= scan.next(); //接收
if(!(str1.matches(regex))){
System.out.println("格式错误,请重新");
}else{
break;
}
}
String str2 = "";
while(true){
System.out.println("输入第二个日期");
str2 = scan.next();
if(!(str2.matches(regex))){
System.out.println("格式错误,请重新");
}else{
break;
}
}
//再判断哪个时间在前,哪个在后
Date d1 = new Date();
Date d2 = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
d1 = sdf.parse(str1);
} catch (ParseException e) {
e.printStackTrace();
} //匹配时间格式
try {
d2=sdf.parse(str2);
} catch (ParseException e) {
e.printStackTrace();
} //匹配时间格式
long l1 = d1.getTime(); //转换为长整型
long l2 = d2.getTime();
if(l1>l2){
System.out.println("时间"+d2+"在前\n 时间"+d1+"在后");
}else{
System.out.println("时间"+d1+"在前\n 时间"+d2+"在后");
}
//并计算输出两个日期之间相差多天
long l3 = Math.abs(l1-l2);
int day = (int)l3/(1000*60*60*24);
System.out.println(d1+"与\n"+d2+"\n 相差"+day+"天");
}
}