My previous question got a lot cons. I will try again, with a code and why it not work.
For example, we have event that will go every 3 month. Event have DateStart, DataEnd and Periodicity.
For example, we have a record:
start = 02/23/2012 22:00:00;
end = 12/31/2012 23:30:00;
periodicity = 3;
Method must return true when current month = February, May, August, November.
Code:
public bool MonthPeriodicityChecker (DateTime start, DateTime end, DateTime dateToCheck, int periodicity)
{
var monthDiff = dateToCheck.Month - startDate.Month;
return (monthDiff-1) % periodicity == 0;
}
This code return true if month in dateToCheck equals April, July, October. It’s skip first month.
UPDATE:
Damn, sorry to all. In the beyond, I have loop that sumulated dates. And this loop start with 1 and add this 1 to start. And next date was 24 February. Therefore, the February not prints( there are checks for number(23) of month too) in my program. Sorry and thanks.
If you want this to trigger in February, May, August and November, you shouldn’t be subtracting one from the difference. Just use:
When the months are equal (February),
0 % 3 == 0. When you’re a multiple of three months out (such as August),6 % 3 == 0.And I’m not sure about C# but some languages don’t act as you may expect when taking the modulus of a negative number, so I’d be doubly safe with:
However, keep in mind that, because you’re only using the month of the year in your calculations, this probably won’t work as expected if you run more than 12 months and your periodicity is not something that divides into 12 cleanly.
Example with starting December 2010 for every five months.
0 % 5 == 0.5 % 5 == 0.10 % 5 == 0.3 % 5 == 3.The upshot of that is that you’ll fire in May, October and December in every year.
You can fix that little problem (if it is a problem for you) by ensuring the years are taken into account, something like:
That also gets rid of the need for adding 12 to get a positive number since the advancing years will ensure that (a jump from December to January will now give you 1 rather than -11), assuming that
dateToCheck.Monthwill always be greater than or equal tostartDate.Month.If there’s the possibility that
dateToCheckmay be lessstartDate, you probably want to check that first and return false as the first step in the above function.