Find recurring date nearest to today - C#

99封情书 提交于 2019-12-06 04:36:13

A little arithmetic should save the day (pun intended):

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.

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 subtract mod days from today to find the spot. If it's greater than half the interval, it means that we need to add interval - mod days to find the spot (which is going to be in the future).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!