c# - What is the exact Excel Days360 algorithm? -
i'm porting calculations excel c# use days360 function (the default/us method). using wikipedia page guide, came code:
public static int days360(datetime a, datetime b) { var daya = a.day; var dayb = b.day; if (islastdayoffebruary(a) && islastdayoffebruary(b)) dayb = 30; if (daya == 31 || islastdayoffebruary(a)) daya = 30; if (daya == 30 && dayb == 31) dayb = 30; return ((b.year - a.year) * 12 + b.month - a.month) * 30 + dayb - daya; } private static bool islastdayoffebruary(datetime date) { if (date.month != 2) return false; int lastday = datetime.daysinmonth(date.year, 2); return date.day == lastday; } i tested (small) range of inputs , results agree excel's native function except if use 2015-02-28 both , b. code returns 0 , excel -2.
my result seems more reasonable @ point, i'd prefer calculate exact same result excel. there might other inputs disagree don't want make special case date.
does know exact algorithm excel uses?
edit: there glaring bug in original code posted unrelated question. had fixed 1 copied wrong file when posting question.
according this wikipedia article microsoft excel days360 function equivalent 30/360 bma/psa. exact results ms excel need implement bma/psa method. have implemented method.
private double days360(datetime startdate, datetime enddate) { int startday = startdate.day; int startmonth = startdate.month; int startyear = startdate.year; int endday = enddate.day; int endmonth = enddate.month; int endyear = enddate.year; if (startday == 31 || islastdayoffebruary(startdate)) { startday = 30; } if (startday == 30 && endday == 31) { endday = 30; } return ((endyear - startyear) * 360) + ((endmonth - startmonth) * 30) + (endday - startday); } private bool islastdayoffebruary(datetime date) { return date.month == 2 && date.day == datetime.daysinmonth(date.year, date.month); }
Comments
Post a Comment