Java Date compareTo()方法与示例

日期类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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值