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.
Asked
Active
Viewed 556 times
-1
-
Please search Stack Overflow before posting. – Basil Bourque May 18 '17 at 17:02
-
Also duplicate of: [Calculate days between two dates in Java 8](http://stackoverflow.com/q/27005861/642706) – Basil Bourque May 18 '17 at 17:05
-
My apologies. @BasilBourque – Abhijeet Mohanty May 19 '17 at 06:01
2 Answers
2
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
-
Thank you for the help. I would like to know if there is a way of passing the present date into LocalDate.of(). – Abhijeet Mohanty May 18 '17 at 08:21
-
-
@ΦXocę웃Пepeúpaツ `Period::getDays` doesn't do what you think it does - your answer is incorrect. For example, `Period.between(LocalDate.of(2015, 1, 1), LocalDate.of(2017, 5, 5)).getDays();` returns 4. – assylias May 18 '17 at 09:37
-
1
1
If you have two LocalDate
s, 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
-
Oh! I have not tested for that as my program just takes a difference of a few days. Thanks a ton. – Abhijeet Mohanty May 18 '17 at 09:55