给定两个日期,计算这两个日期之间的闰年天数的最佳方法是什么。
例如,如果 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# 中有这样的算法,将不胜感激。任何建议和帮助都会很棒。
最佳答案
解决方案是在 python 中,转换为任何其他语言应该不难。
def isLeapYear(year):
if year%4 == 0:
if year%100 == 0:
if year%400 == 0:
return True
else:
return False
else:
return True
else:
return False
def daysBetweenDates(year1, month1, day1, year2, month2, day2):
cumDays = [0,31,59,90,120,151,181,212,243,273,304,334] #cumulative Days by month
leapcumDays = [0,31,60,91,121,152,182,213,244,274,305,335] # Cumulative Days by month for leap year
totdays = 0
if year1 == year2:
if isLeapYear(year1):
return (leapcumDays[month2-1] + day2) - (leapcumDays[month1-1] + day1)
else:
return (cumDays[month2-1] + day2) - (cumDays[month1-1] + day1)
if isLeapYear(year1):
totdays = totdays + 366 - (leapcumDays[month1-1] + day1)
else:
totdays = totdays + 365 - (cumDays[month1-1] + day1)
year = year1 + 1
while year < year2:
if isLeapYear(year):
totdays = totdays + 366
else:
totdays = totdays + 365
year = year + 1
if isLeapYear(year2):
totdays = totdays + (leapcumDays[month2-1] + day2)
else:
totdays = totdays + (cumDays[month2-1] + day2)
return totdays
关于algorithm - 计算闰年中的两个日期之间的天数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1140826/