Created
December 2, 2013 14:02
-
-
Save ararog/7749892 to your computer and use it in GitHub Desktop.
A C# version of Days360 excel function.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
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.
You're right, the method should be like this:
private static bool LastDayOfFebruary(DateTime date)
{
if (date.Month == 2)
{
int lastDay = DateTime.DaysInMonth(date.Year, date.Month);
return date.Day == lastDay;
}
return false;
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.