Earthling Earthling - 2 months ago 4x
C# Question

Calculating days left until the next specified day

In a scenario where you would need to calculate the next 'Billing date' if the DAY (2nd, 25th, etc) is known, how can you calculate the number of days left until the next bill payment?


Tom's bill gets generated on the 4th of every month

What's the best way/logic to calculate the days left until the next bill? For example, if today is the 28th of this month, the result would be 6 days left

What we know:

Bill Generation Date is known

Today's Date is known

What I've done so far:

int billingDay = 4; //The day the bill gets generated every month
DateTime today = DateTime.Today; //Today's date

How would I continue this to calculate the next billing date?

P.S: Sorry if this sounds lame, I just couldn't wrap my head around it :)


I think this works:

private int GetNumDaysToNextBillingDate(int billingDayOfMonth)
    DateTime today = DateTime.Today;

    if (today.Day <= billingDayOfMonth)
        return (new DateTime(today.Year, today.Month, billingDayOfMonth) - today).Days;
        var oneMonthFromToday = today.AddMonths(1);

        var billingDateNextMonth = 
            new DateTime(oneMonthFromToday.Year, 
            oneMonthFromToday.Month, billingDayOfMonth);

        return (billingDateNextMonth - today).Days;