在您需要计算下一个 '计费日期'的场景中,如果日期(2日,25日等)已知,您如何计算距离下一次账单付款剩下的天数?
解释:
Tom的账单在每月4号生成
计算离下一次账单还有多少天的最好方法/逻辑是什么?例如,如果今天是本月28日,结果将是6 days left
我们知道:
票据生成日期已知
今天的日期是已知的
我已经做了什么:
int billingDay = 4; //The day the bill gets generated every month
DateTime today = DateTime.Today; //Today's date
我该如何继续计算下一个计费日期?
p。S:对不起,如果这听起来很蹩脚,我只是无法理解它
我想这行得通:
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;
}
}
如何:
int billingDay = 4;
DateTime today = DateTime.UtcNow;
DateTime billing = today.Day >= billingDay
? new DateTime(today.AddMonths(1).Year, today.AddMonths(1).Month, billingDay)
: new DateTime(today.Year, today.Month, billingDay);
TimeSpan left = billing - today;
这使用了一个循环,但由于它考虑了月份和年份的变化,因此不太容易出错:
int DaysUntilBilling(int billingDay, DateTime referenceDate)
{
int count = 0;
while (referenceDate.AddDays(count).Day != billingDay)
{
count++;
};
return count;
}
如果你总是使用今天的日期,你当然不需要传递DateTime作为参数,但这有助于测试不同的输入,你得到所需的输出:
int billingDay = 4;
DaysUntilBilling(billingDay, DateTime.Now); //26 (today is 9th Aug 2016)
DaysUntilBilling(billingDay, new DateTime(2016, 09, 03); //1
DaysUntilBilling(billingDay, new DateTime(2016, 09, 04); //0
DaysUntilBilling(billingDay, new DateTime(2016, 08, 05); //30
DaysUntilBilling(billingDay, new DateTime(2016, 12, 19); //16
此链接可能对您有所帮助:
https://msdn.microsoft.com/en-us/library/system.datetime.daysinmonth (v = vs.110) . aspx
你可以这样做:
int daysUntilBill = 0;
int billingDay = 4;
DateTime today = DateTime.Today;
if (billingDay > today.Day) {
daysUntilBill = billingDay - today.Day;
} else {
int daysLeftInMonth = DateTime.DaysInMonth(today.Year, today.Month) - today.Day;
daysUntilBill = billingDay + daysLeftInMonth;
}
或者更简洁的
int daysUntilBill = (billingDay >= today.Day)
? billingDay - today.Day
: billingDay + DateTime.DaysInMonth(today.Year, today.Month) - today.Day;
这也可以很好地处理年的结尾,因为它没有试图绕过去。
首先,您需要确定当前日期是在开票日当天还是在开票日之前,以及是否只是减去当月的当前日期。否则,您必须确定下个月的下一个结算日期。
public int DaysToNextBill(int billingDay)
{
var today = DateTime.Today;
if(today.Day <= billingDay)
return billingDay - today.Day;
var nextMonth = today.AddMonth(1);
var nextBillingDate = new DateTime(nextMonth.Year, nextMonth.Month, billingDay)
return (nextBillingDate - today).Days;
}
唯一需要处理的是billingDay
是否大于当前月或下个月的天数