Search code examples
c#datetimetimespanleap-year

Timespan contains leapyear


I have 2 dates, a start (1/1/15) an end (31/12/16)

I need to calculate an amount per day from a total amount (20,000) and a annual amount based on 365 days,

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,

but what I need is to get 730 without the leap day, is there any way of doing this

Thanks Aj


Solution

  • 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;
    }
    

    Your sample:

    int days = DaysDiffMinusLeapYears(new DateTime(15, 1, 1), new DateTime(16,12,31));
    

    Result: 730