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
  • 178
  • 2
  • 19

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
  • 67,715
  • 15
  • 98
  • 113
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
  • 321,522
  • 82
  • 660
  • 783
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
  • 17,229
  • 3
  • 31
  • 44