If you want this to trigger in February, May, August and November, you shouldn’t be subtracting one from the difference. Just use:
return (monthDiff % periodicity) == 0;
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:
public bool MonthPeriodicityChecker (DateTime start, DateTime end,
DateTime dateToCheck, int periodicity)
{
var monthDiff = dateToCheck.Month - startDate.Month + 12; // make positive
return (monthDiff % periodicity) == 0;
}
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.
- December 2010 is okay since the difference is zero:
0 % 5 == 0
. - May 2011 is okay since the difference between May and December is five months:
5 % 5 == 0
. - October 2011 is okay since the difference between October and December is ten months:
10 % 5 == 0
. - March 2012 is not okay. The difference between March and December is three months, not fifteen as has happened in reality:
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:
public bool MonthPeriodicityChecker (DateTime start, DateTime end,
DateTime dateToCheck, int periodicity)
{
// assuming Month returns 1-12 here which is the case for C# I think.
var monthDiff = (dateToCheck.Year * 12 + dateToCheck.Month - 1)
- (startDate.Year * 12 + startDate.Month - 1);
return (monthDiff % periodicity) == 0;
}
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.Month
will always be greater than or equal to startDate.Month
.
If there’s the possibility that dateToCheck
may be less startDate
, you probably want to check that first and return false as the first step in the above function.
0
solved Periodicity of events 2 [closed]