-1

Bearing the risk of being redundant, I would like to know how one can subtract 2 date values and store the result which should be in number of days into an integer. I am using Java for this exercise.

halfer
  • 19,471
  • 17
  • 87
  • 173
Abhijeet Mohanty
  • 314
  • 1
  • 6
  • 16

2 Answers2

2

Use LocalDate and Period:

LocalDate d1 = LocalDate.of(2017, 05, 01);
LocalDate d2 = LocalDate.of(2017, 05, 18);


System.out.println(ChronoUnit.DAYS.between(d1, d2));

you can get the actual date using

LocalDate d1 = LocalDate.now()
ΦXocę 웃 Пepeúpa ツ
  • 45,713
  • 17
  • 64
  • 91
1

If you have two LocalDates, you can use:

longs days = ChronoUnit.DAYS.between(date1, date2);

Note that Period::getDays does something different: for a period of one year and one day, Period::getDays will return 1, not 366!

assylias
  • 310,138
  • 72
  • 642
  • 762