0

I'm trying to create a formula that will give me the distance in days between 2 different days of the week with min/max of +7/-7. So for instance is there a formula to find that the days between this Monday and the coming Thursday is 3 but the distance between this Tuesday and the next Sunday is 5. Also in reverse, the distance between this Wednesday and the previous Monday should return -2, and the distance between this Friday and the previous Saturday is -6. This formula should work for calculating the distance between days for all combinations. Is there such a formula or will I just need to put a series of if/else statements in my code?

Thanks for any help!

weagle08
  • 103
  • 3
  • If this were on stackoverflow they would first ask - what have you tried? Anyway, thinking in Python, you could create a 14 member list eg [m1, t1, ... sa2, su2], identify the input with the day abbreviations and then use the built-in list functions to count the distance between the two inputs. –  Jul 21 '15 at 01:47
  • Maybe you meant "max/min of +7/-7" rather than "min/max of +7/-7"? ${}\qquad{}$ – Michael Hardy Jul 21 '15 at 02:30

2 Answers2

0

How about this:

def calcdis(d1,d2):
    dayls = ['m','tu','w','th','f','sa','su']
    if d1 == d2:
        return 7
    else:
        return dayls.index(d2) - dayls.index(d1)

Some typical user sessions from the prompt:

calcdis('th','m')

calcdis('su','su')

Note: there's no error checking, but I think it does what you want - the specifications are not entirely clear, especially regarding the form of the input.

  • although i was wanting a formula, i did end up using your solution because I didn't have the time to spend trying to figure out a formula. my solution is in javascript – weagle08 Jul 23 '15 at 03:41
0

Thanks to @mistermarko above for a solution. below is my answer in javascript:

function(day, direction){
    var daysOfWeek = [0,1,2,3,4,5,6,0,1,2,3,4,5,6];

    if(day !== null && !isNaN(day) && (day >= 0 && day <= 6)) {
        if(direction === null || isNaN(direction)){
            direction = 1;
        }

        var offset = 0;
        var currentDay = this.getDay();
        var a, b;
        if(direction >= 0) {
            a = daysOfWeek.indexOf(currentDay);
            b = daysOfWeek.indexOf(day, a + 1);
            offset = b - a;
        } else {
            a = daysOfWeek.lastIndexOf(currentDay);
            var tempDays = daysOfWeek.slice(0, a);
            b = tempDays.lastIndexOf(day);
            offset = b - a;
        }

        this.addDays(offset);
    }
}
weagle08
  • 103
  • 3