How to find what period of given timespans is currently How to find what period of given timespans is currently
I've been given 6 hour-and-minute timestamps which define a period of time, lets call them 1 trough 6. (example: 03:13, 05:22, 12:54, 16:55, 20:23, 22:14)
For example: 1st period starts at 03:13 and lasts until 05:22 -1 minute, and so on
Naturally, at the end, periods must cover all 24 hours in a day so the sixth period (which starts at 22:14) will last until 03:13
What is the best/most optimal way to write a function that can tell what period of time we are currently in?
Here is my try (which doesn't work and is suboptimal):
    function currentPeriod(hrs, mins, now) {
       // hrs is an array of integers and they define only hours (3, 5, 12,...)
       // mins is an array of integers and they define minutes (13, 22, 54,...)
       // now is a JavaScript Date
       if(now.getHours() > 0 && now.getHours() < hrs[0]) { return 6; }
       else if(now.getHours() == hrs[0] && now.getMinutes() < mins[0]) { return 6; }
       else if(now.getHours() == hrs[0] && now.getMinutes() >= mins[0]) { return 1; }
    
       else if(now.getHours() > hrs[0] && now.getHours() < hrs[1]) { return 1; }
       else if(now.getHours() == hrs[1] && now.getMinutes() < mins[1]) { return 1; }
       else if(now.getHours() == hrs[1] && now.getMinutes() >= mins[1]) { return 2; }
    
       else if(now.getHours() > hrs[1] && now.getHours() < hrs[2]) { return 2; }
       else if(now.getHours() == hrs[2] && now.getMinutes() < mins[2]) { return 2; }
       else if(now.getHours() == hrs[2] && now.getMinutes() >= mins[2]) { return 3; }
    
       else if(now.getHours() > hrs[2] && now.getHours() < hrs[3]) { return 3; }
       else if(now.getHours() == hrs[3] && now.getMinutes() < mins[3]) { return 3; }
       else if(now.getHours() == hrs[3] && now.getMinutes() >= mins[3]) { return 4; }
    
       else if(now.getHours() > hrs[3] && now.getHours() < hrs[4]) { return 4; }
       else if(now.getHours() == hrs[4] && now.getMinutes() < mins[4]) { return 4; }
       else if(now.getHours() == hrs[4] && now.getMinutes() >= mins[4]) { return 5; }
    
       else if(now.getHours() > hrs[4] && now.getHours() < hrs[5]) { return 5; }
       else if(now.getHours() == hrs[5] && now.getMinutes() < mins[5]) { return 5; }
       else if(now.getHours() == hrs[5] && now.getMinutes() >= mins[5]) { return 6; }
       else if(now.getHours() <= 23 && now.getMinutes() <= 59) { return 6; }
    }
from Stackoverflow
Comments
Post a Comment