Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
A C# version of Days360 excel function.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Project.Helpers
{
public static class DateTimeExtensions
{
public static int Days360(this DateTime? date, DateTime? initialDate)
{
return Days360(date.Value, initialDate.Value);
}
public static int Days360(this DateTime date, DateTime initialDate)
{
var dateA = initialDate;
var dateB = date;
var dayA = dateA.Day;
var dayB = dateB.Day;
if (lastDayOfFebruary(dateA) && lastDayOfFebruary(dateB))
dayB = 30;
if (dayA == 31 && lastDayOfFebruary(dateA))
dayA = 30;
if (dayA == 30 && dayB == 31)
dayB = 30;
int days = (dateB.Year - dateA.Year) * 360 +
((dateB.Month + 1) - (dateA.Month + 1)) * 30 + (dayB - dayA);
return days;
}
private static bool lastDayOfFebruary(DateTime date) {
int lastDay = DateTime.DaysInMonth(date.Year, 2);
return date.Day == lastDay;
}
}
}
@Olli-palkkaus

This comment has been minimized.

Copy link

commented Dec 9, 2014

Thanks for the code snippet, but it is not the same as Excel function. At least the following code results to different results:

Assert.AreEqual(20, DateTimeHelpers.GetDays360(new DateTime(2014, 12, 31), new DateTime(2015, 1, 20)));

Result in Excel is 20, your code results to 19. The reason is, Excel would have switched 31 to 30 actually in most cases - not only in the special cases you are handling above. From documentation:

"U.S. (NASD) method. If the starting date is the last day of a month, it becomes equal to the 30th day of the same month. If the ending date is the last day of a month and the starting date is earlier than the 30th day of a month, the ending date becomes equal to the 1st day of the next month; otherwise the ending date becomes equal to the 30th day of the same month."

@deekumavat

This comment has been minimized.

Copy link

commented Mar 31, 2015

i guess this will work for you
return ((@endYear-@startYear)_12_30)+((@endMonth-1)-(@startMonth-1))*30+(@endDay-@startDay)

Eg :
starte Date=2014/02/17 and End date =2014/10/08
return ((2014-2014)_12_30)+((10-1)-(2-1))*30+(8-17)

@DanielSmithMichigan

This comment has been minimized.

Copy link

commented Mar 31, 2017

private static bool lastDayOfFebruary(DateTime date) {

            int lastDay = DateTime.DaysInMonth(date.Year, 2);
    
            return date.Day == lastDay;
        }

I don't write c#, so forgive me if this is just wrong, but: it doesn't look like your lastDayOfFebruary function actually checks if date is in february, only if date.Day is 28/29.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.