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

从java中的当前日期对象中减去x天,java,date,Java,Date,我遵循stackoverflow的问题,但当n的值大于24时,它并没有给我正确的答案。请给我另一个解决方案并修改该问题 这是密码 Date d = new Date(); Date dateBefore = new Date(d.getTime() - (25 * 24 * 3600 * 1000) ); 当我检查datebefore值时,它会显示日期周二11月26日02:34:18 UTC 2013 现在,如果我将值25更改为24,我将得到正确的日期,即2013年10月8日星期二09:38:

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

这是密码

Date d = new Date();
Date dateBefore = new Date(d.getTime() - (25 * 24 * 3600 * 1000) );
当我检查datebefore值时,它会显示日期周二11月26日02:34:18 UTC 2013


现在,如果我将值25更改为24,我将得到正确的日期,即2013年10月8日星期二09:38:48 UTC

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

int n = //...
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, n);
Date newDate = cal.getTime();
其中
n
可以是正数或负数。因此,要从当前日期减去2天,您将使
n=-2


您可能还需要查找Joda Time

25*24*3600*1000
太大,无法放入
int
中,计算结果为
-2134967296
。例如,您需要将值指定为
long
-
25l*24*3600*1000

greg-449给出了正确答案

仅供参考,如果您愿意使用第三方库,这里有一些易于使用的代码。请参阅使用方法的类

运行时:

Today: 2013-11-01T02:48:01.709-07:00
Minus 25 days: 2013-10-07T02:48:01.709-07:00
关于此源代码和关于Joda时间:

// © 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

这个问题的答案是正确的。如果你没有得到你期望的结果,请将你的代码连同你得到的结果和你期望的结果一起发布在这里。那么告诉我@Aleks G为什么会有这种不同的行为?我接受这个答案,但为什么当我的天数大于24°+1时,我会使用
cal.add(Calendar.DAY\u OF\u MONTH,n)。这更清楚(至少对我来说)@Eng.Fouad是的,我总是发现自己在反复检查this@WaqasAli我会的,但有些人已经有了。记住,日期操纵不仅仅是加减毫秒……谢谢@greg的帮助。
// © 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