Walter Fabio Simoni
Walter Fabio Simoni

Reputation: 5729

Calculate numbers between two date with all month = 30 days

I'm looking for a way to count the numbers of day between two date respecting 30days by month ( even in february, month at 31).

There is some solution in SQL but i'm looking for a solution in c# if possible. Any idea please ?

Example : ( DATE US )

01/01/2016 to 05/31/2016 = 150 days instead of 150.

because there is in this case 5 month, so 5*30 = 150. All month are based on 30days in my case.

Other example :

From 01/16/2016 to 07/17/2016 = 182 instead of 183 (15+30+30+30+30+30+17)

Upvotes: 1

Views: 2006

Answers (3)

Deepak Tambe
Deepak Tambe

Reputation: 49

public static int GetDays(DateTime start, DateTime end) {
    int newDaysDiff = ((360 * (end.Year - start.Year)) + (30 * ((end.Month - start.Month) == 0 ? 0 : (end.Month - start.Month) - 1)));
    int j = 0;
    if (start.Month == end.Month && start.Year == end.Year) {
        if (start.Day == 1 && end.Day == 31) {
            j = (end.Day - start.Day);
        }
        else {
            j = (end.Day - start.Day) + 1;
        }
    }
    else {
        if (start.Day == 1) {
            j = j + 30;
        }
        else {
            j = j + DateTime.DaysInMonth(start.Year, start.Month) - start.Day + 1;
        }
        if (end.Day == 30 || end.Day == 31) {
            j = j + 30;
        }
        else {
            j = j + end.Day;
        }
    }
    newDaysDiff = newDaysDiff + j;
    return newDaysDiff;
}

Upvotes: -1

Nasreddine
Nasreddine

Reputation: 37838

What you're trying to do seems like the same calendar used for the financial market. Here's a solution implementing the 30E/360 ISDA calculation method as it was implemented in the demo XLS they provide on their website (30/360 Day Count Conventions):

var start = new DateTime(2016, 1, 1);
var finish = new DateTime(2016, 05, 31);


var d1 = start.Day == 31 ? 30 : start.Day;
var d2 = finish.Day == 31 && (start.Day == 30 || start.Day == 31) ? 30 : finish.Day;
// actualDaysDiff will be 151 as expected
var actualDaysDiff = (finish - start).TotalDays;
// using the new method newDaysDiff will be 150
int newDaysDiff = ((360 * (finish.Year - start.Year)) + (30 * (finish.Month - start.Month)) + (d2 - d1));

I'm getting the correct result for your other example (which, I think, should be 181 days).

For more information on this topic check the following:

  1. 360-day calendar
  2. C# for Financial Markets

Upvotes: 3

Feras Salim
Feras Salim

Reputation: 438

try this code

var months = endDate.Month - startDate.Month - 1;
var startDateDayes = 30 - startDate.Day;
startDateDayes =startDateDayes ==-1 ? 0 : startDateDayes;//for 31 month days
var endDateDayes = endDate.Day;
var totalDays = startDateDayes + endDateDayes + months * 30;
if (endDate.Year > startDate.Year)
{
    totalDays += 360 * (endDate.Year - startDate.Year);
}

hope it helps

Upvotes: 0

Related Questions