-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,824
  • 17
  • 99
  • 186
Abhijeet Mohanty
  • 334
  • 1
  • 6
  • 21

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 ツ
  • 47,427
  • 17
  • 69
  • 97
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
  • 321,522
  • 82
  • 660
  • 783