-1

I follow this question on stackoverflow but it don't give me correct answer when the value of n is greater than 24. please give me another solutions and modify that question.

This is the code

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

When i check the datebefore value it show me that date Tue Nov 26 02:34:18 UTC 2013

Now if i change the value 25 to 24 i get the correct date which is as Tue Oct 08 09:38:48 UTC 2013

Community
  • 1
  • 1
Waqas Ali
  • 1,642
  • 4
  • 32
  • 55
  • 3
    The answers to that question are correct. If you're not getting the result you expect, post your code here along with the result you're getting and the result you're expecting. – Aleks G Nov 01 '13 at 09:36
  • so tell me @Aleks G why was that different behavior? – Waqas Ali Nov 01 '13 at 09:41

3 Answers3

5

There are probably a few different ways to achieve this, the simplest without resorting to 3rd party libraries might be to use the Calendar API, for example

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

Where n can be a positive or negative number. So to subtract 2 days from the current date, you would make n = -2;

You may also want to look up Joda-Time

MadProgrammer
  • 343,457
  • 22
  • 230
  • 366
5

The value 25 * 24 * 3600 * 1000 is too large to fit in an int and evaluates to -2134967296. You need to specify the value as a long - 25l * 24 * 3600 * 1000 for example.

greg-449
  • 109,219
  • 232
  • 102
  • 145
3

greg-449 gave you the correct answer.

FYI, here's easy code to use if you are willing to use the 3rd-party Joda-Time library. See DateTime class with minusDays() method.

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 );

When run:

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

About this source-code and about 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
Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154