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

发布于 2024-08-06 13:56:36 字数 385 浏览 6 评论 0原文

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

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...               
}

...还是有更好的方法?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

白昼 2024-08-13 13:56:36

Date 实现了类似的本身,所以没有理由将其包装到日历中:

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

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

日期也有方便的 after()before() 方法,使上述比较更易于阅读:

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

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

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

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

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:

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

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

DateTime dt = new DateTime().minusWeeks(2);
if (new DateTime(someDate).isBefore(dt)) {
   ...Code...                           
}
七秒鱼° 2024-08-13 13:56:36

它是有效的,但您对 someDate 有点困惑 - Calendar.setTime 采用 java.util.Date,它只是一个包装器一个long,表示自 1970 年 1 月 1 日午夜(UTC)以来的毫秒数。它不是“采用 MM/dd/yyy 格式”——这是一个字符串表示形式,而不是 java.util.Date。如果它碰巧以 MM/dd/yyyy 格式打印出某些内容,那么这正是 Date.toString 正在为您做的事情 - 它本质上不是该格式的一部分。

顺便说一句,我个人建议您完全避免 java.util.Datejava.util.Calendar 并使用 乔达时间。这是一个更好的 API。

It's valid, but you're slightly confused about someDate - Calendar.setTime takes a java.util.Date, which is just a wrapper around a long indicating 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.toString is doing for you - it's not inherently part of the format.

As an aside, I would personally recommend that you avoid java.util.Date and java.util.Calendar completely and use Joda Time instead. It's a much better API.

白况 2024-08-13 13:56:36

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

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

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

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

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.

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

姜生凉生 2024-08-13 13:56:36

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

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);
    }

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

2019-10-11 早于 2019-10-13

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

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

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

While it was valid to use Calendar in 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.

Link: Oracle tutorial: Date Time explaining how to use java.time.

〆一缕阳光ご 2024-08-13 13:56:36

没关系。您也可以使用 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);

    }

}

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

It's OK. Also you can use before() and 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文