0

I want to subtract days from date in java. But I dont want to use external libraries. I have referred some of questions from stackoverflow but they are suggesting to use external libraries. So I have applied following logic

noOfDays = 24;
Date compareDate = new Date(currentDate - noOfDays * 24 * 60 * 60 * 1000);
System.out.println("compare date " + compareDate);

It is working fine till 24 days.But after 24 days it is giving unexpected result. Is there any solution to this ?

sdk
  • 158
  • 2
  • 18

3 Answers3

4

Use java.util.Calendar. Something like that:

Calendar c = new Calendar()
c.setTime(currentDate);
c.add(Calendar.DAY_OF_MONTH, noOfDays)
compareDate = c.getTime()
Jens
  • 63,364
  • 15
  • 92
  • 104
1

You can use a LocalDate (which is part of the JDK since Java 8):

LocalDate today = LocalDate.now();
LocalDate compareDate = today.minusDays(24);
assylias
  • 310,138
  • 72
  • 642
  • 762
0

You computation is about integers, which won't fit higher values than the max integer value.

Declare your variable as a long :

long noOfDays = 24;
Date compareDate = new Date(currentDate - noOfDays * 24 * 60 * 60 * 1000);
System.out.println("compare date " + compareDate);

However, as the comments said, this is not the best approach for substracting days, so have a look at better solutions in other answers.

Arnaud
  • 16,865
  • 3
  • 28
  • 41