Java 如何检查日期对象是否等于昨天?

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

How to check if a date Object equals yesterday?

javadatecalendarjava-time

提问by tzippy

Right now I am using this code

现在我正在使用此代码

Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
cal.set(cal.get(Calendar.YEAR), cal.get(Calendar.MONTH), cal.get(Calendar.DATE) - 1, 12, 0, 0); //Sets Calendar to "yeserday, 12am"
if(sdf.format(getDateFromLine(line)).equals(sdf.format(cal.getTime())))                         //getDateFromLine() returns a Date Object that is always at 12pm
{...CODE

There's got to be a smoother way to check if the date returned by getdateFromLine() is yesterday's date. Only the date matters, not the time. That's why I used SimpleDateFormat. Thanks for your help in advance!

必须有一种更流畅的方法来检查 getdateFromLine() 返回的日期是否是昨天的日期。重要的是日期,而不是时间。这就是我使用 SimpleDateFormat 的原因。提前感谢您的帮助!

采纳答案by Andrei Fierbinteanu

Calendar c1 = Calendar.getInstance(); // today
c1.add(Calendar.DAY_OF_YEAR, -1); // yesterday

Calendar c2 = Calendar.getInstance();
c2.setTime(getDateFromLine(line)); // your date

if (c1.get(Calendar.YEAR) == c2.get(Calendar.YEAR)
  && c1.get(Calendar.DAY_OF_YEAR) == c2.get(Calendar.DAY_OF_YEAR)) {

This will also work for dates like 1st of January.

这也适用于 1 月 1 日这样的日期。

回答by gruntled

Instead of setting the calendar try this:

而不是设置日历试试这个:

public static void main(String[] args) {
    int DAY_IN_MILLIS = 1000 * 60 * 60 * 24;
    Date date = new Date();
    SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yy");
    String prevDate = dateFormat.format(date.getTime() - DAY_IN_MILLIS);
    String currDate = dateFormat.format(date.getTime());
    String nextDate = dateFormat.format(date.getTime() + DAY_IN_MILLIS);
    System.out.println("Previous date: " + prevDate);
    System.out.println("Current date: " + currDate);
    System.out.println("Next date: " + nextDate);
  }

This should allow you to move forwards and backwards along the calendar

这应该允许您沿着日历向前和向后移动

Then you can simply compare the getDateFromLine(line) to the prevDate value or whatever you like.

然后您可以简单地将 getDateFromLine(line) 与 prevDate 值或您喜欢的任何值进行比较。

回答by chickeninabiscuit

I recommend you consider using Joda-Time. It's freaking way better than the JDK offerings.

我建议您考虑使用Joda-Time。它比 JDK 产品要好得多。

回答by Inv3r53

Something like this roughly:

大致是这样的:

         Calendar c1 = Calendar.getInstance();
         Date d1 = new Date(/* control time */);
         c1.setTime(d1);

        //current date
        Calendar c2 = Calendar.getInstance();

        int day1=c1.get(Calendar.DAY_OF_YEAR);
        int day2=c2.get(Calendar.DAY_OF_YEAR);

       //day2==day1+1 

回答by plowman

I agree with Ash Kim that the Joda-Timelibrary is the way to go if you want to preserve your sanity.

我同意 Ash Kim 的观点,如果您想保持理智,Joda-Time库是您的最佳选择。

import org.joda.time.DateTime;

public static boolean dayIsYesterday(DateTime day) {
    DateTime yesterday = new DateTime().withTimeAtStartOfDay().minusDays(1);
    DateTime inputDay = day.withTimeAtStartOfDay();

    return inputDay.isEqual(yesterday);
}

In this example, if the DateTime dayis from yesterday then dayIsYesterday(day)will return true.

在此示例中,如果 DateTimeday来自昨天,dayIsYesterday(day)则将返回true

回答by Basil Bourque

Avoid java.util.Date & .Calendar

避免 java.util.Date 和 .Calendar

The accepted answeris technically correct but less than optimal. The java.util.Date and .Calendar classes are notoriously troublesome. Avoid them. Use either Joda-Timeor the new java.time package(in Java 8).

接受的答案是技术上是正确的,但不是最佳。java.util.Date 和 .Calendar 类是出了名的麻烦。避开它们。使用Joda-Time或新的java.time 包(在 Java 8 中)。

Time Zone

时区

Time zone is critical in date-time work. If you ignore the issue, the JVM's default time zone will be applied. A better practice is to always specify rather than rely on default. Even when you want the default, explicitly call getDefault.

时区在日期时间工作中至关重要。如果您忽略该问题,则将应用 JVM 的默认时区。更好的做法是始终指定而不是依赖默认值。即使您想要默认值,也请显式调用getDefault.

The beginning of the day is defined by the time zone. A new day dawns earlier in Berlin than in Montréal. So the definition of "today" and "yesterday" requires a time zone.

一天的开始由时区定义。柏林比蒙特利尔更早地迎来了新的一天。所以“今天”和“昨天”的定义需要一个时区。

Joda-Time

乔达时间

Example code in Joda-Time 2.3.

Joda-Time 2.3 中的示例代码。

DateTimeZone timeZone = DateTimeZone.forID( "Europe/Berlin" );
DateTime today = DateTime.now( timeZone ); 

One way to determine yesterday is by converting to LocalDate objects. Another way, shown here, is to represent "yesterday" as a span of time. We define that span as going from the first moment of yesterday up to but not includingthe first moment of today. This approach is called "half-open" where the beginning is inclusiveand the ending is exclusive.

确定昨天的一种方法是转换为 LocalDate 对象。此处显示的另一种方式是将“昨天”表示为时间跨度。我们将这个跨度定义为从昨天的第一个时刻到今天的第一个时刻,但不包括今天的第一个时刻。这种方法被称为“半开”,其中开头是包容性的,结尾是排斥性的

Subtract a day to get to yesterday (or day before).

减去一天到昨天(或前一天)。

DateTime yesterdayStartOfDay = today.minusDays( 1 ).withTimeAtStartOfDay();
Interval yesterdayInterval = new Interval( yesterdayStartOfDay, today.withTimeAtStartOfDay() );

Convert your target java.util.Date object to a Joda-Time DateTime object. Apply a time zone to that new object, rather than rely on applying JVM's default time zone. Technically the time zone here in this case is irrelevant, but including a time zone is a good habit.

将您的目标 java.util.Date 对象转换为 Joda-Time DateTime 对象。将时区应用于该新对象,而不是依赖于应用 JVM 的默认时区。从技术上讲,在这种情况下,这里的时区无关紧要,但包括时区是一个好习惯。

DateTime target = new DateTime( myJUDate, timeZone );

Test if the target lands within the interval of yesterday.

测试目标是否在昨天的间隔内着陆。

boolean isYesterday = yesterdayInterval.contains( target );

Obviously this approach with half-open span of time works with more than just "yesterday", such as "this week", "last month", and so on.

显然,这种半开放时间跨度的方法不仅仅适用于“昨天”,例如“本周”、“上个月”等等。

Updated:The Joda-Time project is now in maintenance mode. The team advises migration to the java.time classes. See the java.time solution in the correct Answer by Przemek.

更新:Joda-Time 项目现在处于维护模式。该团队建议迁移到 java.time 类。请参阅 Przemek 的正确答案中的 java.time 解决方案。

回答by Allen

I have found it a little confuse when I use this way to test this method

当我使用这种方式来测试这种方法时,我发现它有点混乱

 Calendar now = new GregorianCalendar(2000, 1, 1);
 now.add(Calendar.DATE, -1);

 SimpleDateFormat format= new SimpleDateFormat("yyyy-MM-dd");
 System.out.println(format.format(now.getTime()));

my expect is to print 1999-12-31,but the actual is 2001-1-31I guess Calendar.add() only deal with day in month.

我的期望是打印1999-12-31,但实际是2001-1-31我猜 Calendar.add() 只处理一个月中的一天。

But the actual error is the way I create the Calendar object. In Calendar ,month start with 0,the variable now's value is 2001-2-1, I was so self-conceit as not to print it.when I found something was wrong. correct way to create a Calendar is :

但实际的错误是我创建 Calendar 对象的方式。在日历中,月份从0开始,变量现在的值是2001-2-1,我太自负了以至于没有打印它。当我发现有问题时。创建日历的正确方法是:

 Calendar now = new GregorianCalendar(2000, Calendar.JANUARY, 1);

The Calendar was so weird to an ex C# programmer :(

日历对于前 C# 程序员来说太奇怪了:(

回答by Przemek

java.time

时间

Using java.timeframework built into Java 8

使用java.time内置于 Java 8 的框架

LocalDate now = LocalDate.now(); //2015-11-24
LocalDate yesterday = LocalDate.now().minusDays(1); //2015-11-23

yesterday.equals(now); //false
yesterday.equals(yesterday); //true

Official Oracle LocalDatetutorialstates

Oracle 官方LocalDate教程说明

The equals method should be used for comparisons.

应该使用 equals 方法进行比较。

If you're working with objects such as LocalDateTime, ZonedDateTime, or OffsetDateTime, you may convert to LocalDate.

如果你正在使用的对象,如工作LocalDateTimeZonedDateTime或者OffsetDateTime,你可以转换为LocalDate

LocalDateTime.now().toLocalDate(); # 2015-11-24