This question already has an answer here:
这个问题在这里已有答案:
- Calculating the difference between two Java date instances 43 answers
计算两个Java日期实例之间的差异43个答案
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.
承担冗余的风险,我想知道如何减去2个日期值并将结果存储在整数中。我正在使用Java进行此练习。
2 个解决方案
#1
1
If you have two LocalDate
s, you can use:
如果您有两个LocalDates,则可以使用:
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!
请注意,Period :: getDays会做一些不同的事情:对于一年和一天的期间,Period :: getDays将返回1,而不是366!
#2
#1
1
If you have two LocalDate
s, you can use:
如果您有两个LocalDates,则可以使用:
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!
请注意,Period :: getDays会做一些不同的事情:对于一年和一天的期间,Period :: getDays将返回1,而不是366!