Calculate the distance between days of the week

987 Views Asked by At

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!

2

There are 2 best solutions below

1
On BEST ANSWER

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.

0
On

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);
    }
}