Search code examples
phpmathradix

PHP check if 3 counts later (date)(Cycle of 1-7)


I'm currently making a system which needs to know if a certain variable has been stored less than 3 days ago, and if it has, return true. When the variable was initially saved, it was set as date('N'), which is the day of the week, in numerical format. (1 = monday, 7 = sunday according to php docs.)

However, how would I figure out that it's been 3 or more days later? My main dilemma is this: if the variable is day 5, and it is currently day 4, that means the cycle of 1 week is almost complete (6 days have passed) - however I can't figure out how to do that in php. Another example would be the variable is day 7, and it is currently day 1 - numerically speaking, inclusively there are 6 "days" in between the two values, but in reality, it has only been one day as after 7 comes 1.

P.S. I reset the values every week, which is why I do not bother to save things like month, or year.


Solution

  • This can actually be solved in the current state with the help of mathematics. Let's first take a look at good and bad values.

    • stored on 1: good: 2, 3, 4 bad: 1, 5, 6, 7
    • stored on 2: good: 3, 4, 5 bad: 1, 2, 6, 7
    • stored on 6: good: 7, 1, 2 bad: 3, 4, 5, 6
    • stored on 7: good: 1, 2, 3 bad: 4, 5, 6, 7

    If you subtract the stored value from the current, you'll see that good - stored = 1, 2 or 3 for standard cases (no overlapping) and good - stored = -6, -5, -4 (maximum overlapping).

    Meanwhile bad - stored = 4, 5, 6 or 0 (no overlapping) and bad - stored = -3, -2, -1 or 0 (maximum overlapping).

    So you want your result to be either in the interval [1, 3] or [-6, -4], which could be done like this

    //somwhere $storedN is defined
    $todayN = date('N');
    $result = $todayN - $storedN;
    if (($result > 0 && $result < 4) || ($result > -7 && $result < -3)) {
    //            no overlap                        overlap
        // valid
    }