查找最接近今天的重复日期 - C#
听起来像是家庭作业?不,不是。我为此制定了逻辑,但当日期跨度多年时,效果不佳。 基本上它应该如何工作,
StartDate: 1/1/2012
FinishDate: 1/10/2012
RecurringInterval: 2 ( In days)
输出将是:
1/6/2012
如果今天的日期 (Date.Now
) 是 2012 年 1 月 5 日
(假设格式为 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;
Sounds like a homework? no it's not. I worked up the logic for this but not such a performant one when dates are span over years.
Basically here is how it should work,
StartDate: 1/1/2012
FinishDate: 1/10/2012
RecurringInterval: 2 ( In days)
Output would be:
1/6/2012
if Todays date (Date.Now
) is 1/5/2012
( Assuming format MM/dd/yyyy
). Check would end when finish date is reached. If no dates match within given time period, today's Date must be returned. Dead simple but not a efficient one.
What is wrong with this?
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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一点算术就可以拯救世界(双关语):
查看实际操作。
其作用是计算距离今天的“复发点”还有多少天(变量
mod
)。显然这将是一个数字 >= 0 且 <间隔。如果是间隔的一半或更小,则意味着最近的重复点早于今天,在这种情况下,从今天减去mod
天即可找到该点。如果它大于间隔的一半,则意味着我们需要添加interval - mod
天来找到该位置(这将是未来的情况)。A little arithmetic should save the day (pun intended):
See it in action.
What this does is calculate how many days away from a "recurrence spot" today is (variable
mod
). This is obviously going to be a number >= 0 and < interval. If it's half the interval or less, it means the closest recurrence spot is earlier than today, in which case subtractmod
days from today to find the spot. If it's greater than half the interval, it means that we need to addinterval - mod
days to find the spot (which is going to be in the future).