如果 DAY (第2,第25等)已知,您需要计算下一个'结算日期'的情况,如何计算在下一次支付账单之前剩余的天数?
解释
汤姆的账单每月4日生成
计算下一个账单剩余天数的最佳方法/逻辑是什么?例如,如果今天是本月的第28天,结果将是剩余6天
我们所知道的事情:
比尔生成日期已知
今天的日期已知
到目前为止我做了什么:
int billingDay = 4; //The day the bill gets generated every month
DateTime today = DateTime.Today; //Today's date
如何继续计算下一个结算日期?
P:对不起,如果这听起来很蹩脚,我就无法绕过它:)答案 0 :(得分:3)
我认为这有效:
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;
}
}
答案 1 :(得分:2)
怎么样:
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;
答案 2 :(得分:1)
此链接可能会对您有所帮助:
https://msdn.microsoft.com/en-us/library/system.datetime.daysinmonth(v=vs.110).aspx
你可以做的是这样的事情:
self.game.deal()
或稍微简洁
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;
}
这也正确地处理了年末,因为它不会试图环绕。
答案 3 :(得分:1)
首先,您需要确定当前日期是否在结算日之前或之前,以及它是否只是减去当月的当天。否则,您必须确定下个月的下一个结算日期。
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
大于当前或下个月的天数。
答案 4 :(得分:1)
这会使用一个循环但不太容易出错,因为它考虑了月份和年份的变化:
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