java 早于一个月前的日期

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

Date earlier than a month ago

javadate

提问by Micha? Ziober

How to check whether the given date is earlier than a month ago? What is the fastest algorithm? I have to take into account that different months have different numbers of days.

如何检查给定日期是否早于一个月前?最快的算法是什么?我必须考虑到不同的月份有不同的天数。

回答by OscarRyz

Updated to Java 8

更新到 Java 8

The class LocalDateclass can be used:

可以使用类LocalDate类:

LocalDate aDate = LocalDate.parse("2017-01-01");
return aDate.isBefore( LocalDate.now().minusMonths(1));

For previous versions, the Calendar class would work.

对于以前的版本, Calendar 类可以工作。

Calendar calendar = Calendar.getInstance();
calendar.add( Calendar.MONTH ,  -1 );
return aDate.compareTo( calendar.getTime() ) < 0;

Sample code:

示例代码:

import static java.lang.System.out;
import java.time.LocalDate;

public class Sample {
    public static void main( String [] args ) {
        LocalDate aMonthAgo = LocalDate.now().minusMonths(1);
        out.println( LocalDate.parse("2009-12-16").isBefore(aMonthAgo));
        out.println( LocalDate.now().isBefore(aMonthAgo));
        out.println( LocalDate.parse("2017-12-24").isBefore(aMonthAgo));
    }
}

Prints

印刷

true
false
false

回答by Vinko Vrsalovic

Using Joda Time:

使用Joda 时间

DateTime dt1 = new DateTime(); //Now
DateTime dt2 = new DateTime(2009,9,1,0,0,0,0); //Other date
if (dt1.plusMonths(-1) > dt2) {
    //Date is earlier than a month ago
}

回答by Basil Bourque

tl;dr

tl;博士

LocalDate.now( ZoneId.of( "America/Montreal"  )
         .minusMonths( 1 )
         .isAfter( LocalDate.parse( "2017-01-23" ) )

java.time

时间

The modern approach uses the java.time classes rather than the troublesome legacy classes such as Date& Calendar.

现代方法使用 java.time 类而不是麻烦的遗留类,例如Date& Calendar

Today

今天

First get the current date. The LocalDateclass represents a date-only value without time-of-day and without time zone.

首先获取当前日期。该LocalDate级表示没有时间一天和不同时区的日期,唯一的价值。

A time zone is crucial in determining a date. For any given moment, the date varies around the globe by zone. For example, a few minutes after midnight in Paris Franceis a new day while still “yesterday” in Montréal Québec.

时区对于确定日期至关重要。对于任何给定时刻,日期因地区而异。例如,在法国巴黎午夜过后几分钟是新的一天,而在魁北克蒙特利尔仍然是“昨天” 。

Specify a proper time zone namein the format of continent/region, such as America/Montreal, Africa/Casablanca, or Pacific/Auckland. Never use the 3-4 letter abbreviation such as ESTor ISTas they are nottrue time zones, not standardized, and not even unique(!).

以、、 或等格式指定正确的时区名称。永远不要使用 3-4 个字母的缩写,例如或因为它们不是真正的时区,不是标准化的,甚至不是唯一的(!)。continent/regionAmerica/MontrealAfrica/CasablancaPacific/AucklandESTIST

ZoneId z = ZoneId.of( "America/Montreal" );
LocalDate today = LocalDate.now( z );

Calculating month-ago

一个月前的计算

Next, determine the date a month ago.

接下来,确定一个月前日期

LocalDate monthAgo = today.minusMonths( 1 ) ;

Here are the rules used by LocalDate::minusMonths, quoted from Java 8 class doc:

以下是 使用的规则LocalDate::minusMonths,引用自 Java 8 类文档:

This method subtracts the specified amount from the months field in three steps:

  1. Subtract the input months from the month-of-year field

  2. Check if the resulting date would be invalid

  3. Adjust the day-of-month to the last valid day if necessary

For example, 2007-03-31 minus one month would result in the invalid date 2007-02-31. Instead of returning an invalid result, the last valid day of the month, 2007-02-28, is selected instead.

此方法分三步从月份字段中减去指定的金额:

  1. 从月份字段中减去输入月份

  2. 检查结果日期是否无效

  3. 如有必要,将月份日期调整为最后一个有效日期

例如,2007-03-31 减去一个月将导致无效日期 2007-02-31。不是返回无效结果,而是选择该月的最后一个有效日期 2007-02-28。

Or, perhaps in your business rules you meant "30 days" instead of a calendar month.

或者,也许在您的业务规则中,您的意思是“30 天”而不是日历月。

LocalDate thirtyDaysAgo = today.minusDays( 30 ) ;

Input

输入

You are given a date. That should be passed to your code as a LocalDateobject.

给你一个约会。这应该作为LocalDate对象传递给您的代码。

LocalDate ld = LocalDate.of( 2017 , Month.JANUARY , 23 ) ;

If coming from a String, use the standard ISO 8601formats. For other formats, search Stack Overflow for DateTimeFormatterclass.

如果来自字符串,请使用标准ISO 8601格式。对于其他格式,请搜索 Stack Overflow 以获取DateTimeFormatter类。

LocalDate ld = LocalDate.parse( "2017-01-23" ) ;

Comparison

比较

Now compare. Call the isBefore, isEqual, isAftermethods.

现在比较。调用isBefore, isEqual,isAfter方法。

Boolean outdated = ld.isBefore( monthAgo ) ;

Performance

表现

As for the issue of performance raised in the Question: Don't worry about it. This month-ago calculation and comparison is veryunlikely to be a bottleneck in your app. Avoid premature optimization.

至于问题中提出的性能问题:别担心。本月同期的计算和比较是不太可能在您的应用程序的瓶颈。避免过早优化



About java.time

关于 java.time

The java.timeframework is built into Java 8 and later. These classes supplant the troublesome old legacydate-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

java.time框架是建立在Java 8和更高版本。这些类取代了麻烦的旧的遗留日期时间类,例如java.util.Date, Calendar, & SimpleDateFormat

The Joda-Timeproject, now in maintenance mode, advises migration to the java.timeclasses.

现在处于维护模式Joda-Time项目建议迁移到java.time类。

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

要了解更多信息,请参阅Oracle 教程。并在 Stack Overflow 上搜索许多示例和解释。规范是JSR 310

Where to obtain the java.time classes?

从哪里获得 java.time 类?

The ThreeTen-Extraproject extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

ThreeTen-额外项目与其他类扩展java.time。该项目是未来可能添加到 java.time 的试验场。你可能在这里找到一些有用的类,比如IntervalYearWeekYearQuarter,和更多