计算闰年的两个日期之间的天数
给定两个日期,计算这两个日期之间属于闰年的天数的最佳方法是什么。
例如,如果 d1 = 12/1/2007 且 d2 = 1/31/2008,则 d1 和 d2 之间的总天数将为 62,闰年的天数将为 31。
另一个示例是,如果d1 = 12/1/2007 且 d2 = 6/30/2012 那么 d1 和 d2 之间的总天数将为 1674,闰年的天数将为 548。
我已经有函数来计算如果特定年份是闰年,并且有一个计算两个日期之间天数的函数。
如果有人在 Delphi (Pascal) 或 C/C++/C# 中有这样的算法,我们将不胜感激。 任何建议和帮助都会很棒。
Given two dates, what is the best method to calculate the number of days between those two dates that fall in a leap year.
For example if d1 = 12/1/2007 and d2 = 1/31/2008 then the total number of days between d1 and d2 would be 62 and the number of days that fall in a leap year would be 31.
Another example is if d1 = 12/1/2007 and d2 = 6/30/2012 then the total number of days between d1 and d2 would be 1674 and the number of days that fall in a leap year would be 548.
I already have function to calculate if a specific year is a leap year and and a function to calculate the number of days between two dates.
If anyone has such a algorithm in Delphi (Pascal) or C/C++/C# that would be greatly appreciated. Any suggestions and assistance would be great.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
解决方案是使用Python,并且转换为任何其他语言应该不难。
The solution is in python, and it shouldn't be hard to convert to any other language.
这是我的伪代码版本,使用您的函数 -
is_leap_year, days_ Between
。 正如评论者指出的那样,正确编写这些函数是很棘手的。Here's my pseudo code version using your functions for -
is_leap_year, days_between
. As a commenter noted, these are tricky functions to write correctly.一个天真的方法是:
检查你的开始年份。 如果是闰年,请计算从当天到 12 月 31 日(含)的天数。 如果不是,则将年份加 1,直到起始年份等于结束年份。然后检查年份。 如果是闰年,则开始计算天数,如果不是则增加年份。 一旦当前年份和结束年份相同,则检查当前(==结束)年份是否为闰年。 如果是,则计算从一月到结束月的月份天数,否则会破坏算法。 一旦当前月份是您的结束月份,请计算您的天数。
A naive approach would be:
Check your start year. If it's a leap year, count the number of days from your current day to December 31 (inclusive). If not, until your starting year equals your ending year, increment the year by 1. Then, check the year. If it is a leap year, start counting days, if not increment the year. Once the current year and ending year are the same, then check to see if the current (== ending) year is a leap year. If it is, count days in months from January to the ending month, otherwise break the algorithm. Once your current month is your ending month, count your days.