compareto java date_Java Date compareTo()用法及代码示例

Java Date类的compareTo()方法比较两个日期并将它们排序。

用法:

public int compareTo(Date anotherDate)

参数:该函数接受单个参数anotherDate,该参数指定要比较的日期。

返回值:该函数提供以下指定的三个返回值:

如果参数Date等于此Date,则返回值0。

如果此Date在Date参数之前,则返回小于0的值。

如果此Date在Date参数之后,则返回大于0的值。

异常:如果anotherDate为null,则该函数引发一个异常,该异常为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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值