用java写任意选择两个日期用程序判断他们的先后顺序。大神求指教

2025-01-03 20:45:43
推荐回答(2个)
回答1:

public class Test {
public static void main(String s[]) {
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String dateStr1 = "2014-05-14 11:11:11";
String dateStr2 = "2014-05-14 12:12:12";
Date date1 = sdf.parse(dateStr1);
Date date2 = sdf.parse(dateStr2);
if(date1.getTime()-date2.getTime()>0) {
System.out.println("dateStr2 比 dateStr1 早");
}else{
System.out.println("dateStr1 比 dateStr2 早");
}
} catch (Exception ex) {
ex.printStackTrace();
}

}
}

回答2:

JAVA API里直接提供了方法,如下:
Date date = new Date();
date.after(when);
date.before(when);