Earthling - 6 months ago 23

C# Question

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?

**Explanation:**

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

Bill Generation Date is known

Today's Date is known

`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 :)

Answer

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;
}
else
{
var oneMonthFromToday = today.AddMonths(1);
var billingDateNextMonth =
new DateTime(oneMonthFromToday.Year,
oneMonthFromToday.Month, billingDayOfMonth);
return (billingDateNextMonth - today).Days;
}
}
```