概述
日期类compareTo()方法 (Date Class compareTo() method)
compareTo() method is available in java.util package.
compareTo()方法在java.util包中可用。
compareTo() method is used to compare this date and the given date (d2) or in other words, we can this method compare two Date objects.
compareTo()方法用于比较此日期和给定日期(d2),换句话说,我们可以使用此方法比较两个Date对象。
compareTo() method is a non-static method, it is accessible with the class object only and if we try to access the method with the class name then we will get an error.
compareTo()方法是一种非静态方法,只能通过类对象访问,如果尝试使用类名称访问该方法,则会收到错误消息。
compareTo() method may throw an exception at the time of comparing two Date objects.
比较两个Date对象时, compareTo()方法可能会引发异常。
NullPointerException: This exception may throw when the given parameter (d2) is null exists.
NullPointerException :如果给定参数(d2)为null,则可能引发此异常。
Syntax:
句法:
public int compareTo(Date d2);
Parameter(s):
参数:
Date d2 – represents another date to be compared with.
日期d2 –表示要比较的另一个日期。
Return value:
返回值:
The return type of this method is int, it returns any one of the given values.
此方法的返回类型为int ,它返回给定值中的任何一个。
It returns 0, when d1 = d2.
当d1 = d2时,它返回0。
It returns negative value, when d1 < d2.
当d1 <d2时,它返回负值。
It returns positive value, when d1 > d2.
当d1> d2时,它返回正值。
Example:
例:
// Java program to demonstrate the example
// of int compareTo() method of Date
import java.util.*;
public class CompareToDate {
public static void main(String[] args) {
// create two Date object with two dates
Date this_date = new Date(2016, 8, 20);
Date given_date = new Date(2010, 11, 30);
// By using compareTo() method is to compare
// this_date and the given_date
int result = this_date.compareTo(given_date);
// Display result
System.out.println("this_date.compareTo(given_date): " + result);
}
}
Output
输出量
this_date.compareTo(given_date): 1
翻译自: https://www.includehelp.com/java/date-compareto-method-with-example.aspx
最后
以上就是多情犀牛为你收集整理的Java Date compareTo()方法与示例的全部内容,希望文章能够帮你解决Java Date compareTo()方法与示例所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
发表评论 取消回复