从java中的当前日期对象中减去x天

时间:2013-11-01 09:34:09

标签: java date

我在stackoverflow上关注this问题,但是当n的值大于24时,它没有给我正确答案。请给我另一个解决方案并修改该问题。

这是代码

Date d = new Date();
Date dateBefore = new Date(d.getTime() - (25 * 24 * 3600 * 1000) );

当我检查datebefore值时,它会显示该日期 Tue Nov 26 02:34:18 UTC 2013

现在,如果我将值25更改为24,我会得到正确的日期,如 Tue Oct 08 09:38:48 UTC 2013

3 个答案:

答案 0 :(得分:5)

可能有几种不同的方法可以实现这一点,最简单的方法是不使用第三方库,可能是使用Calendar API,例如

int n = //...
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, n);
Date newDate = cal.getTime();

n可以是正数或负数。因此,要从当前日期减去2天,您需要n = -2;

您可能还想查找Joda-Time

答案 1 :(得分:5)

25 * 24 * 3600 * 1000太大而无法放入int并评估为-2134967296。您需要将值指定为long - 25l * 24 * 3600 * 1000,例如。

答案 2 :(得分:3)

greg-449给了你正确答案。

仅供参考,如果您愿意使用第三方Joda-Time库,可以使用这些简单的代码。使用DateTime方法查看minusDays()课程。

org.joda.time.DateTime today = new org.joda.time.DateTime();
System.out.println("Today: " + today );

org.joda.time.DateTime dateBefore = today.minusDays(25);
System.out.println("Minus 25 days: " + dateBefore );

运行时:

Today: 2013-11-01T02:48:01.709-07:00
Minus 25 days: 2013-10-07T02:48:01.709-07:00

关于此源代码和关于Joda-Time:

// © 2013 Basil Bourque. This source code may be used freely forevery by anyone taking full responsibility for doing so.

// Joda-Time - The popular alternative to Sun/Oracle's notoriously bad date, time, and calendar classes bundled with Java 7 and earlier.
// http://www.joda.org/joda-time/

// Joda-Time will become outmoded by the JSR 310 Date and Time API introduced in Java 8.
// JSR 310 was inspired by Joda-Time but is not directly based on it.
// http://jcp.org/en/jsr/detail?id=310

// By default, Joda-Time produces strings in the standard ISO 8601 format.
// https://en.wikipedia.org/wiki/ISO_8601