查找两个日期之间的日期的算法 [英] Algorithm to find the days between two dates
问题描述
我正在处理一个学校问题,以找出算法来查找两个给定日期之间的日期,然后用Java实现该日期。
I was working with a school question to figure out the algorithm to find the days between two given dates which would then be implemented in Java.
感兴趣的算法在此处找到:
http://www.sunshine2k.de/ article / coding / datediffindays / calcdiffofdatesindates.html
(第4点)
The algorithm of interest was found here: http://www.sunshine2k.de/articles/coding/datediffindays/calcdiffofdatesindates.html (Point 4)
这是效率更高的算法之一,因为它的最少实施过程中要考虑的条件。我知道它在这种情况下是如何工作的,但是我无法完全确定在其他任何地方都使用起点/参考点,因为似乎简单的减法就可以完成大多数工作。
It was one of the more efficient algorithms because it would have the least conditions to consider during the implementation. I understand how it works in this context, but I couldn't quite wrap my mind around the use of an origin/reference point anywhere else because it seems that a simple subtraction would get most jobs done.
例如。要找到9和5之间的差异,
我可以做 9-5
而不是
Eg. To find the difference between 9 and 5,
I could just do 9-5
instead of
ref = 1
差异=(9-ref)-(5-ref)
问题:为什么在这种情况下使用此参考点/原点?我还可以考虑使用此参考/起源点解决问题的其他情况吗?
Question: Why does using this reference/origin point work in this situation? What other situations can I consider using this reference/origin point to solve problems?
推荐答案
软件工程的第一个规则是唐重新发明轮子。
First rule of Software Engineering is "Don't reinvent the wheel".
在Java 8和更高版本中获取两个日期之间的日期是微不足道的,无需编写自己的算法:
Getting the days between two dates in Java 8 and later is trivial, there's no need to code your own algorithm:
LocalDate d2 = LocalDate.now();
LocalDate d1 = LocalDate.of(1950, Month.JANUARY, 1);
long days = d1.until(d2,ChronoUnit.DAYS);
甚至更好
long days = ChronoUnit.DAYS.between(d1, d2);
这篇关于查找两个日期之间的日期的算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!