听起来像是作业?不,这不对。我为此制定了逻辑,但是当日期跨越多年时,我并没有这样的表现。 基本上这是它应该如何工作,
StartDate: 1/1/2012
FinishDate: 1/10/2012
RecurringInterval: 2 ( In days)
输出为:
1/6/2012
如果今天的日期(Date.Now
)为1/5/2012
(假设格式MM/dd/yyyy
)。达到完成日期后,检查将结束。如果在给定时间段内没有匹配日期,则必须返回今天的日期。死简单但不高效。
if (!_isRecurring)
return DateTime.UtcNow;
DateTime initialDate = _startDate;
DateTime finalDate = _finishDate;
int recurringDays = _recurringInteral;
/*
* start Date + recurring interval falls between start date and finishdate then get its date
*/
do
{
//add recurring day to start date
initialDate = initialDate.AddDays(recurringDays);
//check if it falls in between start days and end days
if(initialDate <= finalDate)
break;
} while (initialDate <= finalDate);
//return the first occurance of the recurring day
return initialDate;
答案 0 :(得分:8)
一点算术应该可以节省一天(双关语):
var start = new DateTime(2012, 1, 1);
var end = new DateTime(2012, 10, 1);
var interval = 2; // days
var today = DateTime.Today;
var diff = (int)((today - start).TotalDays);
var mod = diff % interval;
var correction = TimeSpan.FromDays((mod > interval / 2 ? interval : 0) - mod);
var result = today + correction > end ? today : today + correction;
Console.Out.WriteLine("Result is: {0}", result);
<强> See it in action 强>
这样做的目的是计算今天“复发点”的天数(变量mod
)。这显然是一个数字&gt; = 0和&lt;间隔。如果它是间隔的一半或更小,则意味着最接近的复发点早于今天,在这种情况下从今天减去mod
天以找到该点。如果它大于间隔的一半,则意味着我们需要添加interval - mod
天才能找到该位置(将来会有这样的位置)。