如何在java中比较两个日期和时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22039991/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:12:56  来源:igfitidea点击:

How to compare two dates along with time in java

javadatetimecompare

提问by user2636874

I have two Dateobjects with the below format.

我有两个Date具有以下格式的对象。

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
String matchDateTime = sdf.parse("2014-01-16T10:25:00");
Date matchDateTime = null;

try {
    matchDateTime = sdf.parse(newMatchDateTimeString);
} catch (ParseException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

// get the current date
Date currenthDateTime = null;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
Date dt = new Date();
String currentDateTimeString = dateFormat.format(dt);
Log.v("CCCCCurrent DDDate String is:", "" + currentDateTimeString);

try {                   
    currenthDateTime = sdf.parse(currentDateTimeString);
} catch (ParseException e) {
    // TODO Auto-generated catch block 
    e.printStackTrace();
}

Now I want to compare the above two dates along with time. How should I compare in Java.

现在我想将上述两个日期与时间进行比较。我应该如何在 Java 中进行比较。

Thanks

谢谢

采纳答案by fge

Since Dateimplements Comparable<Date>, it is as easy as:

由于Dateimplements Comparable<Date>,它就像:

date1.compareTo(date2);

As the Comparablecontract stipulates, it will return a negative integer/zero/positive integer if date1is considered less than/the same as/greater than date2respectively (ie, before/same/after in this case).

按照Comparable合约规定,如果date1被认为小于/等于/大于date2分别(即,在这种情况下之前/相同/之后),它将返回一个负整数/零/正整数。

Note that Datehas also .after()and .before()methods which will return booleans instead.

请注意,Date也有.after().before()方法将返回布尔值。

回答by Nambi

Use compareTo()

compareTo()

Return Values

返回值

0 if the argument Date is equal to this Date; a value less than 0 if this Date is before the Date argument; and a value greater than 0 if this Date is after the Date argument.

0 如果参数 Date 等于这个 Date;如果此日期在日期参数之前,则为小于 0 的值;如果此日期在日期参数之后,则该值大于 0。

Like

喜欢

if(date1.compareTo(date2)>0) 

回答by Vibin

An Alternative is....

另一种选择是......

Convert both dates into milliseconds as below

将两个日期转换为毫秒,如下所示

Date d = new Date();
long l = d.getTime();

Now compare both long values

现在比较两个长值

回答by MaximeF

An alternative is Joda-Time.

另一种选择是Joda-Time

Use DateTime

使用日期时间

DateTime date = new DateTime(new Date());
date.isBeforeNow();
or
date.isAfterNow();

回答by sujith s

 // Get calendar set to the current date and time
Calendar cal = Calendar.getInstance();

// Set time of calendar to 18:00
cal.set(Calendar.HOUR_OF_DAY, 18);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);

// Check if current time is after 18:00 today
boolean afterSix = Calendar.getInstance().after(cal);

if (afterSix) {
    System.out.println("Go home, it's after 6 PM!");
}
else {
    System.out.println("Hello!");
}

回答by Ole V.V.

The other answers are generally correct and all outdated. Do use java.time, the modern Java date and time API, for your date and time work. With java.time your job has also become a lot easier compared to the situation when this question was asked in February 2014.

其他答案通常是正确的,而且都已经过时了。一定要使用 java.time,现代 Java 日期和时间 API,为您的日期和时间工作。与 2014 年 2 月提出这个问题时的情况相比,有了 java.time,您的工作也变得容易多了。

    String dateTimeString = "2014-01-16T10:25:00";
    LocalDateTime dateTime = LocalDateTime.parse(dateTimeString);
    LocalDateTime now = LocalDateTime.now(ZoneId.systemDefault());

    if (dateTime.isBefore(now)) {
        System.out.println(dateTimeString + " is in the past");
    } else if (dateTime.isAfter(now)) {
        System.out.println(dateTimeString + " is in the future");
    } else {
        System.out.println(dateTimeString + " is now");
    }

When running in 2020 output from this snippet is:

在 2020 年运行时,此代码段的输出为:

2014-01-16T10:25:00 is in the past

2014-01-16T10:25:00 过去了

Since your string doesn't inform of us any time zone or UTC offset, we need to know what was understood. The code above uses the device' time zone setting. For a known time zone use like for example ZoneId.of("Asia/Ulaanbaatar"). For UTC specify ZoneOffset.UTC.

由于您的字符串没有通知我们任何时区或 UTC 偏移量,我们需要知道所理解的内容。上面的代码使用设备的时区设置。对于已知的时区,例如使用ZoneId.of("Asia/Ulaanbaatar"). 对于 UTC 指定ZoneOffset.UTC.

I am exploiting the fact that your string is in ISO 8601 format. The classes of java.time parse the most common ISO 8601 variants without us having to give any formatter.

我正在利用您的字符串采用 ISO 8601 格式这一事实。java.time 的类解析最常见的 ISO 8601 变体,而我们不必提供任何格式化程序。

Question: For Android development doesn't java.time require Android API level 26?

问题:对于 Android 开发,java.time 不需要 Android API 级别 26 吗?

java.time works nicely on both older and newer Android devices. It just requires at least Java 6.

java.time 在较旧和较新的 Android 设备上都能很好地工作。它只需要至少Java 6

  • In Java 8 and later and on newer Android devices (from API level 26) the modern API comes built-in.
  • In non-Android Java 6 and 7 get the ThreeTen Backport, the backport of the modern classes (ThreeTen for JSR 310; see the links at the bottom).
  • On (older) Android use the Android edition of ThreeTen Backport. It's called ThreeTenABP. And make sure you import the date and time classes from org.threeten.bpwith subpackages.
  • 在 Java 8 及更高版本和更新的 Android 设备(从 API 级别 26)中,现代 API 是内置的。
  • 在非 Android Java 6 和 7 中获得 ThreeTen Backport,现代类的 backport(ThreeTen for JSR 310;请参阅底部的链接)。
  • 在(较旧的)Android 上使用 ThreeTen Backport 的 Android 版本。它被称为 ThreeTenABP。并确保从org.threeten.bp子包中导入日期和时间类。

Links

链接