Java Date compareTo()方法及示例
Java Date类 的 compareTo() 方法对两个日期进行比较,并对它们进行排序。
语法
public int compareTo(Date anotherDate)
参数: 该函数接受一个单一的参数 anotherDate ,指定要比较的日期。
返回值: 该函数给出三个返回值,具体如下。
- 如果参数Date等于这个Date,则返回值为0。
- 如果这个Date在参数Date之前,它返回一个小于0的值。
- 如果这个Date在Date参数之后,则返回一个大于0的值。
异常: 如果 AnotherDate 为空,该函数会抛出一个异常,即 NullPointerException 。
下面的程序演示了上述的函数。
// Java code to demonstrate
// compareTo() function of Date class
import java.util.Date;
import java.util.Calendar;
public class GfG {
// main method
public static void main(String[] args)
{
// creating a Calendar object
Calendar c = Calendar.getInstance();
// set Month
// MONTH starts with 0 i.e. ( 0 - Jan)
c.set(Calendar.MONTH, 11);
// set Date
c.set(Calendar.DATE, 05);
// set Year
c.set(Calendar.YEAR, 1996);
// creating a date object with specified time.
Date dateOne = c.getTime();
System.out.println("Date 1: "
+ dateOne);
// creating a date of object
// storing the current date
Date currentDate = new Date();
System.out.println("Date 2: "
+ currentDate);
// compares
System.out.println("On Comparison: "
+ currentDate
.compareTo(dateOne));
}
}
输出:
Date 1: Thu Dec 05 08:17:55 UTC 1996
Date 2: Wed Jan 02 08:17:55 UTC 2019
On Comparison: 1
// Java code to demonstrate
// compareTo() function of Date class
import java.util.Date;
public class GfG {
// main method
public static void main(String[] args)
{
// creating a date of object
// stospecified datent date
Date currentDate = new Date();
System.out.println("Date 1: " + currentDate);
// specifiedDate is assigned to null.
Date specifiedDate = null;
System.out.println("Date 2: " + specifiedDate);
System.out.println("Passing null as parameter: ");
try {
// throws NullPointerException
System.out.println(currentDate
.compareTo(specifiedDate));
}
catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
输出:
Date 1: Wed Jan 02 08:18:02 UTC 2019
Date 2: null
Passing null as parameter:
Exception: java.lang.NullPointerException