问题
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;
回答1:
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).
来源:https://stackoverflow.com/questions/8860089/find-recurring-date-nearest-to-today-c-sharp