Timespan包含leap年 [英] Timespan contains leapyear
本文介绍了Timespan包含leap年的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有2个日期,开始(1/1/15),结束(31/12/16)
I have 2 dates, a start (1/1/15) an end (31/12/16)
我需要从总金额(20,000)和每年的总金额(以365天为基础)计算每天的金额,
I need to calculate an amount per day from a total amount (20,000) and a annual amount based on 365 days,
我正在使用Timespan获取开始日期和结束日期之间的日期,但是在这种情况下,由于2006年是a年,因此它返回731(365 + 366),
I'm using Timespan to get the days between start and end dates, but in this case it returns 731 (365 + 366) as 2006 is a leap year,
但是我需要的是在没有the日的情况下获得730,有什么办法做到
but what I need is to get 730 without the leap day, is there any way of doing this
谢谢
推荐答案
也许有一种更有效的方法,但是可以按预期工作:
Perhaps there is a more efficient approach but this works as expected:
public static int DaysDiffMinusLeapYears(DateTime dt1, DateTime dt2)
{
DateTime startDate = dt1 <= dt2 ? dt1.Date : dt2.Date;
DateTime endDate = dt1 <= dt2 ? dt2.Date : dt1.Date;
int days = (endDate - startDate).Days + 1;
int daysDiff = Enumerable.Range(0, days)
.Select(d => startDate.AddDays(d))
.Count(day => day.Day != 29 || day.Month != 2);
return daysDiff;
}
您的样本:
int days = DaysDiffMinusLeapYears(new DateTime(15, 1, 1), new DateTime(16,12,31));
结果:730
这篇关于Timespan包含leap年的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文