如何在 Java 中比较两个日期?
在 Java 中,可以使用 Comparable 接口的 compareTo() 方法 来比较两个日期。如果两个日期相等,此方法返回“0”;如果 date1 在 date2 之后,则返回一个“大于 0”的值;如果 date1 在 date2 之前,则返回一个“小于 0”的值。
语法
int compareTo(T o)
示例
import java.text.*;
import java.util.Date;
public class CompareTwoDatesTest {
public static void main(String[] args) throws ParseException {
SimpleDateFormat sdformat = new SimpleDateFormat("yyyy-MM-dd");
Date d1 = sdformat.parse("2019-04-15");
Date d2 = sdformat.parse("2019-08-10");
System.out.println("The date 1 is: " + sdformat.format(d1));
System.out.println("The date 2 is: " + sdformat.format(d2));
if(d1.compareTo(d2) > 0) {
System.out.println("Date 1 occurs after Date 2");
} else if(d1.compareTo(d2) < 0) {
System.out.println("Date 1 occurs before Date 2");
} else if(d1.compareTo(d2) == 0) {
System.out.println("Both dates are equal");
}
}
}
在上面的示例中,日期 d1 发生在日期 d2 之前,因此它可以在控制台中显示“日期 1 发生在日期 2 之前”。
输出
The date 1 is: 2019-04-15 The date 2 is: 2019-08-10 Date 1 occurs before Date 2
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
JavaScript
PHP