-1

私はstackoverflowでこの質問に従いますが、nの値が24より大きい場合、正しい答えが得られません。別の解決策を教えて、その質問を修正してください。

これがコードです

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

datebefore の値を確認すると、2013 年 11 月 26 日火曜日 02:34:18 UTCという日付が表示されます

ここで、値 25 を 24 に変更すると、正しい日付が取得されます。これは、Tue Oct 08 09:38:48 UTC 2013 です。

4

3 に答える 3

5

25 * 24 * 3600 * 1000が大きすぎて に収まらず、intと評価され-2134967296ます。たとえば、値をlong-として指定する必要があります。25l * 24 * 3600 * 1000

于 2013-11-01T09:44:37.097 に答える
3

greg-449 さんが正解しました。

参考までに、サードパーティのJoda-Timeライブラリを使用する場合に使用する簡単なコードを次に示します。MinusDays()メソッドを使用したDateTimeクラスを参照してください。

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
于 2013-11-01T09:52:32.417 に答える