Java 比较日期是否早于 24 小时

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

Compare if a date is less than 24 hours before

javacalendar

提问by Biscuit128

I am trying to compare two calendars in java to decide if one of them is >= 24 hours ago. I am unsure on the best approach to accomplish this.

我正在尝试比较 Java 中的两个日历,以确定其中一个日历是否 >= 24 小时前。我不确定实现这一目标的最佳方法。

            //get todays date
            Date today = new Date();
            Calendar currentDate = Calendar.getInstance();
            currentDate.setTime(today);

            //get last update date
            Date lastUpdate = profile.getDateLastUpdated().get(owner);
            Calendar lastUpdatedCalendar = Calendar.getInstance();
            lastUpdatedCalendar(lastUpdate);

            //compare that last hotted was < 24 hrs ago from today?

采纳答案by oschlueter

you could use Date.getTime(), here's an example:

你可以使用Date.getTime(),这是一个例子:

public final static long MILLIS_PER_DAY = 24 * 60 * 60 * 1000L;
public static void main(String args[]) throws Exception {
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    Date date1 = sdf.parse("2009-12-31");
    Date date2 = sdf.parse("2010-01-31");

    boolean moreThanDay = Math.abs(date1.getTime() - date2.getTime()) > MILLIS_PER_DAY;

    System.out.println(moreThanDay);
}

回答by Basil Bourque

tl;dr

tl;博士

Instant now = Instant.now();
Boolean isWithinPrior24Hours = 
    ( ! yourJUDate.toInstant().isBefore( now.minus( 24 , ChronoUnit.HOURS) ) ) 
    && 
    ( yourJUDate.toInstant().isBefore( now ) 
) ;

Details

细节

The old date-time classes (java.util.Date/.Calendar, java.text.SimpleDateFormat, etc.) have proven to be be confusing and flawed. Avoid them.

旧的日期时间类(java.util.Date/.Calendar、java.text.SimpleDateFormat 等)已被证明是令人困惑和有缺陷的。避开它们。

For Java 8 and later, use java.time framework built into Java. For earlier Java, add the Joda-Time framework to your project.

对于 Java 8 及更高版本,请使用 Java 中内置的 java.time 框架。对于早期的 Java,将 Joda-Time 框架添加到您的项目中。

You can easily convert between a java.util.Date and either framework.

您可以轻松地在 java.util.Date 和任一框架之间进行转换。

java.time

时间

The java.timeframework built into Java 8 and later supplants the troublesome old java.util.Date/.Calendar classes. The new classes are inspired by the highly successful Joda-Timeframework, intended as its successor, similar in concept but re-architected. Defined by JSR 310. Extended by the ThreeTen-Extraproject. See the Tutorial.

Java 8 及更高版本中内置的java.time框架取代了麻烦的旧 java.util.Date/.Calendar 类。新类的灵感来自非常成功的Joda-Time框架,作为其继承者,概念相似但重新构建。由JSR 310定义。由ThreeTen-Extra项目扩展。请参阅教程

The Instantclass represents a moment on the timeline in UTC. If you meant to ask for literally 24 hours rather than "a day", then Instantis all we need.

Instant类表示UTC时间线上的时刻。如果您想从字面上要求 24 小时而不是“一天”,那么这Instant就是我们所需要的。

Instant then = yourJUDate.toInstant();
Instant now = Instant.now();
Instant twentyFourHoursEarlier = now.minus( 24 , ChronoUnit.HOURS );
// Is that moment (a) not before 24 hours ago, AND (b) before now (not in the future)?
Boolean within24Hours = ( ! then.isBefore( twentyFourHoursEarlier ) ) &&  then.isBefore( now ) ;

If you meant "a day" rather than 24 hours, then we need to consider time zone. A day is determined locally, within a time zone. Daylight Saving Time (DST)and other anomalies mean a day is not always 24 hours long.

如果您的意思是“一天”而不是 24 小时,那么我们需要考虑时区。一天是在当地确定的,在一个时区内。夏令时 (DST)和其他异常情况意味着一天并不总是 24 小时。

Instant then = yourJUDate.toInstant();
ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime now = ZonedDateTime.now( zoneId );
ZonedDateTime oneDayAgo = now.minusDays( 1 );
Boolean within24Hours = ( ! then.isBefore( oneDayAgo ) ) &&  then.isBefore( now ) ;

Another approach would use the Intervalclass found in the ThreeTen-Extra project. That class represents a pair of Instantobjects. The class offers methods such as containsto perform comparisons.

另一种方法是使用IntervalThreeTen-Extra 项目中的类。该类表示一对Instant对象。该类提供了诸如contains执行比较之类的方法。

Joda-Time

乔达时间

The Joda-Timelibrary works in a similar fashion to java.time, having been its inspiration.

乔达时间图书馆工作以类似的方式来java.time,已被其灵感。

DateTime dateTime = new DateTime( yourDate ); // Convert java.util.Date to Joda-Time DateTime.
DateTime yesterday = DateTime.now().minusDays(1);
boolean isBeforeYesterday = dateTime.isBefore( yesterday );

Or, in one line:

或者,在一行中:

boolean isBeforeYesterday = new DateTime( yourDate).isBefore( DateTime.now().minusDays(1) );