Search code examples
algorithmdatecalendarmumps

What's the language-agnostic algorithm for finding the "Same day of week last year"


I want to find the "same day of the week last year". I'm sure that question is going to have litany of subtleties that I've not yet begun to think about but I believe this question is likely a common one.

Here are a few use cases where someone might want to use this algorithm:

Example 1

I'm a manager at a Walmart. I want to find out how many kitten mittens I sold the same day last year. I know that kitten mitten purchases are closely related to day of week and week of year. Thus I want to know "how many kitten mittens do I need to stock for tomorrow "the first Tuesday in January".

Example 2

I'm a nurse at a hospital. I want to determine how many patients are coming in each day next week so I can better align staff with bed demand. I know that there are strong trends with how many patients arrive at the hospital by day of week, and I want to see how many patients we had "the third Friday of November" last year.

I feel like this is a standard problem people have to have come across. Is there a best approach to this challenge? I can imagine issues where in the current year there are five Fridays in say November, and the last year there were only four, so you would not be able to report in that manner.

What is a language-independent (although if you're curious, I would be implementing this in M) approach to this algorithm?


Solution

  • There is a function that returns week day number. In Cache it's $zd(date,10), in GT.M there should be similar one. All you need to do is to correct your date using this function:

    set currentDate=+$h
    set currentWeekDay=$zd(currentDate,10)
    set dateAboutYearAgo=currentDate-365
    set weekDayAboutYearAgo=$zd(dateAboutYearAgo,10)
    set sameWeekDayAboutYearAgo=dateAboutYearAgo-weekDayAboutYearAgo+currentWeekDay