Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the amount of days between two given days of the week

I want to find out how many days there are between two given days of the week.

This looks to be a case for a well executed slice method; but I just can't get my head around it.

const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

let today = 'Thursday'
let dispatch = 'Monday'
let remaining = '???'

console.log(`${remaining} Days until the next dispatch`)

Monday to Thursday is easy enough :

let remaining = days.slice(days.indexOf('Monday'), days.indexOf('Thursday')).length + 1

But Thursday to Monday (for example) needs some logic that I can't figure out.

like image 214
Mark Notton Avatar asked Mar 04 '23 22:03

Mark Notton


2 Answers

You can drop the slice and the if and make use of some modulo arithmetics.

const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

function getDays(start, end) {
    return (days.indexOf(end) + days.length - days.indexOf(start)) % days.length + 1;
}
console.log(getDays("Monday", "Thursday")); // 4
console.log(getDays("Thursday", "Monday")); // 5

If you decide you want Monday to Thursday to just be 3 instead of 4 (which might be more natural depending on the context) just drop the +1 from the end.

like image 100
Nikola Dimitroff Avatar answered Mar 08 '23 23:03

Nikola Dimitroff


I think you can directly subtract two .indexOf() values without calling .slice(), no? Like this:

const days = ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday']

let today = 'Thursday'
let dispatch = 'Monday'
let remaining = days.indexOf(dispatch) - days.indexOf(today) + 1
if (remaining < 1) {
    remaining += days.length
}

console.log(`${remaining} Days until the next dispatch`)
like image 29
Xiaoyi Cao Avatar answered Mar 09 '23 01:03

Xiaoyi Cao