在 Java 中找出过去 30 天、60 天和 90 天

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

Find out Last 30 Days, 60 Days and 90 Days in java

javadate

提问by Gnaniyar Zubair

How to get last 30 / 60 / 90 days records from given date in java?

java - 如何从Java中的给定日期获取最后30 / 60 / 90天的记录?

I have some records with receivedDate. I want to fetch the records for last 30 or 60 or 90 days from received Date. How to resolve it?

我有一些接收日期的记录。我想从接收日期获取过去 30 或 60 或 90 天的记录。如何解决?

采纳答案by cletus

Use java.util.Calendar.

使用java.util.Calendar

Date today = new Date();
Calendar cal = new GregorianCalendar();
cal.setTime(today);
cal.add(Calendar.DAY_OF_MONTH, -30);
Date today30 = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, -60);
Date today60 = cal.getTime();
cal.add(Calendar.DAY_OF_MONTH, -90);
Date today90 = cal.getTime();

回答by neesh

not sure where you are fetching your data from but to compute the date that is say 30 days from now you can use the Calendar class's add function like so:

不确定您从哪里获取数据,但要计算从现在起 30 天后的日期,您可以使用 Calendar 类的 add 函数,如下所示:

c.add(Calendar.DAY_OF_MONTH, -30); //assuming c is of type java.util.Calendar

c.add(Calendar.DAY_OF_MONTH, -30); //假设c是java.util.Calendar类型

Now to figure out if a particular date is between today and 30 days ago you can use the before() and after() functions to figure out if the date was before today but after the 30th day before today.

现在要确定特定日期是否在今天和 30 天前之间,您可以使用 before() 和 after() 函数来确定日期是否在今天之前但在今天之前的第 30 天之后。

回答by Daniel C. Sobral

Honestly, I recommend you use Joda as your date&time library. Not only it has a superior API, but it understands (ie, has classes for) concepts like periods, duration and things like that.

老实说,我建议您使用 Joda 作为您的日期和时间库。它不仅有一个卓越的 API,而且它理解(即,有类)诸如周期、持续时间和诸如此类的概念。

回答by Dalton Dias

Using the Calendar, I needed to pick up the date minus N days from the current date. The best way was:

使用日历,我需要从当前日期开始减去 N 天。最好的办法是:

public Date getDateVariation(Integer variation, Date currentDate) {
    Calendar c = Calendar.getInstance();
    c.setTime(currentDate);
    c.add(Calendar.DAY_OF_YEAR, - (variation));
    return c.getTime();
}

Variationis o N day that i want 10/30/60/120 days.

变化是我想要 10/30/60/120 天的 N 天。

回答by Basil Bourque

tl;dr

tl;博士

LocalDate                       // Represent a date-only value, without time-of-day and without time zone.
.now(                           // Capture today's date as seen in the wall-clock time used by the people of a particular region (a time zone).
    ZoneId.of( "Asia/Tokyo" )   // Specify the desired/expected zone.
)                               // Returns a `LocalDate` object.
.minus(                         // Subtract a span-of-time.
    Period.ofDays( 30 )         // Represent a span-of-time unattached to the timeline in terms of years-months-days.
)                               // Returns another `LocalDate` object.

Avoid legacy date-time classes

避免遗留的日期时间类

The bundled java.util.Date & .Calendar group of classes are notoriously troublesome. Avoid them.

捆绑的 java.util.Date 和 .Calendar 类组是出了名的麻烦。避开它们。

java.time

时间

The modern approach uses the java.timeclasses built into Java 8 and later, and back-ported to Java 6 & 7.

现代方法使用Java 8 及更高版本中内置的java.time类,并反向移植到 Java 6 和 7。

LocalDate

LocalDate

The LocalDateclass represents a date-only value without time-of-day and without time zoneor offset-from-UTC.

LocalDate级表示没有时间的天,没有一个日期,只值时区偏移从-UTC

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.

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

If no time zone is specified, the JVM implicitly applies its current default time zone. That default may change at any momentduring runtime(!), so your results may vary. Better to specify your desired/expected time zone explicitly as an argument. If critical, confirm the zone with your user.

如果未指定时区,JVM 会隐式应用其当前默认时区。该默认值可能会在运行时随时更改(!),因此您的结果可能会有所不同。最好将您想要/预期的时区明确指定为参数。如果关键,请与您的用户确认该区域。

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

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

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

If you want to use the JVM's current default time zone, ask for it and pass as an argument. If omitted, the code becomes ambiguous to read in that we do not know for certain if you intended to use the default or if you, like so many programmers, were unaware of the issue.

如果您想使用 JVM 的当前默认时区,请询问它并作为参数传递。如果省略,代码读起来会变得模棱两可,因为我们不确定您是否打算使用默认值,或者您是否像许多程序员一样没有意识到这个问题。

ZoneId z = ZoneId.systemDefault() ;  // Get JVM's current default time zone.

Or specify a date. You may set the month by a number, with sane numbering 1-12 for January-December.

或指定日期。您可以通过数字设置月份,对于 1 月至 12 月,合理的编号为 1-12。

LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ;  // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.

Or, better, use the Monthenum objects pre-defined, one for each month of the year. Tip: Use these Monthobjects throughout your codebase rather than a mere integer number to make your code more self-documenting, ensure valid values, and provide type-safety. Ditto for Year& YearMonth.

或者,更好的是使用Month预定义的枚举对象,一年中的每个月都有一个。提示:Month在整个代码库中使用这些对象而不仅仅是整数,以使您的代码更具自文档性、确保有效值并提供类型安全。同上Year& YearMonth

LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;

Date math

日期数学

You can define a span-of-time in terms of years-months-days with the Periodclass.

您可以根据类的年-月-日定义时间跨度Period

Period days_30 = Period.ofDays( 30 ) ;
Period days_60 = Period.ofDays( 60 ) ;
Period days_90 = Period.ofDays( 90 ) ;

You can add and subtract a Periodto/from a LocalDate, resulting in another LocalDateobject. Call the LocalDate::plusor LocalDate::minusmethods.

您可以Period从 a 中添加和减去 a LocalDate,从而产生另一个LocalDate对象。调用LocalDate::plusLocalDate::minus方法。

ZoneId z = ZoneId.of( "Africa/Tunis" ) ;
LocalDate today = LocalDate.now( z ) ;
LocalDate ago_30 = today.minus( days_30 ) ;
LocalDate ago_60 = today.minus( days_60 ) ;
LocalDate ago_90 = today.minus( days_90 ) ;

You more directly call LocalDate.minusDays, but I suspect the named Periodobjects will make your code more readable and self-documenting.

您更直接地调用LocalDate.minusDays,但我怀疑命名Period对象将使您的代码更具可读性和自我记录。

LocalDate ago = today.minusDays( 30 ) ;

JDBC

JDBC

Sounds like you are querying a database. As of JDBC 4.2 and later, you can exchange java.timeobjects with your database. For a database column of a data type akin to the SQL-standard standard DATE(a date-only value, without time-of-day and without time zone), use LocalDateclass in Java.

听起来您正在查询数据库。从 JDBC 4.2 及更高版本开始,您可以与数据库交换java.time对象。对于类似于 SQL 标准标准的数据类型的数据库列DATE(仅限日期的值,没有时间和时区),请使用LocalDateJava 中的类。

myPreparedStatement.setObject( … , ago_30 ) ;

Retrieval:

恢复:

LocalDate ld = myResultSet.getObject( … , LocalDate.class ) ;


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

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

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

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

You may exchange java.timeobjects directly with your database. Use a JDBC drivercompliant with JDBC 4.2or later. No need for strings, no need for java.sql.*classes.

您可以直接与您的数据库交换java.time对象。使用符合JDBC 4.2或更高版本的JDBC 驱动程序。不需要字符串,不需要类。java.sql.*

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,和更多



Joda-Time

乔达时间

UPDATE:The Joda-Time library is now in maintenance-mode. Its creator, Stephen Colebourne, went on to lead the JSR 310 and java.timeimplementation based on lessons learned with Joda-Time. I leave this section intact as history, but advise using java.timeinstead.

更新:Joda-Time 库现在处于维护模式。它的创建者 Stephen Colebourne根据 Joda-Time 的经验教训继续领导 JSR 310 和java.time实现。我将这一部分作为历史完整保留,但建议使用java.time代替。

Here is some example code using the Joda-Time2.3 library's LocalDateclass.

下面是一些使用Joda-Time2.3 库的LocalDate类的示例代码。

LocalDate now = LocalDate.now();
LocalDate thirty = now.minusDays( 30 );
LocalDate sixty = now.minusDays( 60 );
LocalDate ninety = now.minusDays( 90 );

Dump to console…

转储到控制台...

System.out.println( "now: " + now );
System.out.println( "thirty: " + thirty );
System.out.println( "sixty: " + sixty );
System.out.println( "ninety: " + ninety );

When run…

运行时…

now: 2014-03-26
thirty: 2014-02-24
sixty: 2014-01-25
ninety: 2013-12-26

Time Zone

时区

The beginning and ending of a day depends on your time zone. A new day dawns in Paris earlier than in Montréal.

一天的开始和结束取决于您所在的时区。新的一天在巴黎比蒙特利尔更早开始。

By default, the LocalDate class uses your JVM's default time zone to determine the current date. Alternatively, you may pass a DateTimeZone object.

默认情况下,LocalDate 类使用 JVM 的默认时区来确定当前日期。或者,您可以传递一个 DateTimeZone 对象。

LocalDate localDate = new LocalDate( DateTimeZone.forID( "Europe/Paris" ) );

回答by ?ukasz W?ódarczyk

private static Date daysAgo(int days) {
    GregorianCalendar gc = new GregorianCalendar();
    gc.add(Calendar.DATE, -days);
    return gc.getTime();
}

回答by roy

code to get future date

获取未来日期的代码

    public String futureDateByFourMonths() {
    Date currentDate = new Date();

    Calendar c = Calendar.getInstance();
    c.setTime(currentDate);

    c.add(Calendar.MONTH, 4);
    c.add(Calendar.DATE, 1); 
    c.add(Calendar.HOUR, 1);
    c.add(Calendar.MINUTE, 1);
    c.add(Calendar.SECOND, 1);

    Date currentDatePlusOne = c.getTime();

    return dateFormat.format(currentDatePlusOne);

}

Just change month and minus the number of months

只需更改月份并减去月份数

public String pastDateByFourMonths() {

    Date currentDate = new Date();

    Calendar c = Calendar.getInstance();
    c.setTime(currentDate);

    c.add(Calendar.MONTH, -4);
    c.add(Calendar.DATE, -1); 
    c.add(Calendar.HOUR, 1);
    c.add(Calendar.MINUTE, 1);
    c.add(Calendar.SECOND, 1);

    Date currentDatePlusOne = c.getTime();

    return dateFormat.format(currentDatePlusOne);

}

I found this solution somewhere and modified it for my need

我在某处找到了这个解决方案并根据我的需要修改了它