Java 我应该使用 Calendar.compareTo() 来比较日期吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1505496/
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-12 13:34:50  来源:igfitidea点击:

Should I use Calendar.compareTo() to compare dates?

javadatecalendar

提问by

Is it a valid way of comparing dates:

这是比较日期的有效方法:

Calendar someCalendar1 = Calendar.getInstance(); // current date/time
someCalendar1.add(Calendar.DATE, -14);

Calendar someCalendar2 = Calendar.getInstance();
someCalendar2.setTime(someDate); // someDate is in the format of MM/dd/yyyy

if(someCalendar2.compareTo(someCalendar1) < 0){
   ...Code...               
}

...or is there a better approach?

……或者有更好的方法吗?

采纳答案by ChssPly76

Dateimplements comparable itself so there's no reason to wrap it into calendar:

Date实现了可比本身,因此没有理由将其包装到日历中:

Calendar someCalendar1 = Calendar.getInstance(); // current date/time
someCalendar1.add(Calendar.DATE, -14);

if (someDate.compareTo(someCalendar1.getTime()) < 0) {
   ...Code...                           
}

Date also has convenient after()and before()methods that make the above comparison easier to read:

Date 也有方便的after()before()方法,使上面的比较更容易阅读:

if (someDate.before(someCalendar1.getTime())) {
   ...Code...                           
}

Finally, if you're dealing with date / time a lot, do consider using Joda Timeinstead of built-in java classes. It's MUCH more convenient and functional:

最后,如果您经常处理日期/时间,请考虑使用Joda Time而不是内置的 Java 类。它更加方便和实用:

DateTime dt = new DateTime().minusWeeks(2);
if (new DateTime(someDate).isBefore(dt)) {
   ...Code...                           
}

回答by Nico

回答by Jon Skeet

It's valid, but you're slightly confused about someDate- Calendar.setTimetakes a java.util.Date, which is just a wrapper around a longindicating the number of milliseconds since midnight Jan 1st 1970, UTC. It's not "in the format MM/dd/yyy" - that's a string representation, not a java.util.Date. If it happens to print something out in the format MM/dd/yyyy, that's just what Date.toStringis doing for you - it's not inherently part of the format.

它是有效的,但你稍稍感到困惑someDate-Calendar.setTime需要java.util.Date,这仅仅是围绕着一个包装long指示从午夜开始1970年1月1日,UTC毫秒数。它不是“格式为 MM/dd/yyy”——这是一个字符串表示,而不是java.util.Date. 如果它碰巧以 format 打印出一些东西MM/dd/yyyy,那正是Date.toString为你做的——它本质上不是格式的一部分。

As an aside, I would personally recommend that you avoid java.util.Dateand java.util.Calendarcompletely and use Joda Timeinstead. It's a muchbetter API.

顺便说一句,我个人建议您避免java.util.Datejava.util.Calendar完全使用Joda Time。这是一个很大更好的API。

回答by JuanZe

It's OK. Also you can use before() and after():

没关系。您也可以使用 before() 和 after():

package demo.so;

import java.util.Date;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;

public class Tester {

    public static void main(String[] args) throws Exception {

    Calendar someCalendar1 = Calendar.getInstance(); // current date/time
    someCalendar1.add(Calendar.DATE, -11);

    DateFormat df = new SimpleDateFormat("MM/dd/yyyy");
    Date someDate =   df.parse("10/08/2009");

    Calendar someCalendar2 = Calendar.getInstance();
    someCalendar2.setTime(someDate);

    String cal1 = df.format(someCalendar1.getTime());
    String cal2 = df.format(someCalendar2.getTime());

    if (someCalendar1.equals(someCalendar2))
        System.out.println( cal1 + " is the same as " + cal2);
    if (someCalendar1.after(someCalendar2))
        System.out.println(cal1 + " is after " + cal2);
    if (someCalendar1.before(someCalendar2))
        System.out.println(cal1 + " is before " + cal2);

    }

}

But you shouldn't use Date, is deprecated and a source of troubles with dates handling. Build your own wrapper for GregorianCalendar or use some good library, like Joda.

但是您不应该使用 Date,它已被弃用并且是日期处理问题的根源。为 GregorianCalendar 构建您自己的包装器或使用一些好的库,如 Joda。

回答by Dean J

As one example of why Joda is better, take Daylight Savings Time.

作为 Joda 更好的一个例子,以夏令时为例。

If you're measuring "one day" as 1000 * 60 * 60 * 24 milliseconds, the Date library - and the Calendar library - both forget that there's one day in the year with 25 hours, and another with 23. You will occasionally screw up date calculations if you rely solely on the Java classes built into the J2SE API.

如果您将“一天”测量为 1000 * 60 * 60 * 24 毫秒,则日期库 - 和日历库 - 都会忘记一年中有一天是 25 小时,而另一天是 23 小时。您偶尔会搞砸如果您仅依赖于 J2SE API 中内置的 Java 类,则更新计算。

Joda is half likely to be the drop-in replacement for GregorianCalendar, Calendar, and Date in a future version of Java.

在 Java 的未来版本中,Joda 有一半可能是 GregorianCalendar、Calendar 和 Date 的直接替代品。

回答by Ole V.V.

It's an old question now. For it to be helpful to the readers of today and tomorrow it needs a modern answer. That's what I am providing here.

现在是个老问题了。为了对今天和明天的读者有所帮助,它需要一个现代的答案。这就是我在这里提供的。

java.time

时间

    LocalDate someDate1 = LocalDate.now(ZoneId.of("Africa/Lusaka"))
            .minusDays(14);
    LocalDate someDate2 = LocalDate.of(2019, Month.OCTOBER, 11);

    if (someDate2.isBefore(someDate1)) {
        System.out.println("" + someDate2 + " is before " + someDate1);
    }

When I ran this code today, the output was:

当我今天运行这段代码时,输​​出是:

2019-10-11 is before 2019-10-13

2019-10-11 是在 2019-10-13 之前

While it was valid to use Calendarin 2009, the class was always poorly designed and is now long outdated. I certainly recommend that no one uses it anymore. Instead use java.time, the modern Java date and time API.

虽然它Calendar在 2009年有效,但该类的设计一直很差,现在已经过时了。我当然建议没有人再使用它。而是使用 java.time,现代 Java 日期和时间 API。

Link:Oracle tutorial: Date Timeexplaining how to use java.time.

链接:Oracle 教程:解释如何使用 java.time 的日期时间