Determining time remaining until bus departs












0















For our digital signage system, I'd like to show how long until the next bus departs. I've built the array that holds all the times and successfully (maybe not elegantly or efficiently) gotten it to change all that to show how much time is remaining (positive or negative) until each listed departure.



I need a nudge in the right direction as to how to determine which bus is next based on the current time. If there is a bus in 7 minutes, I only need to display that one, not the next one that leaves in 20 minutes.



I was thinking perhaps a for loop that looks at the array of remaining times and stops the first time it gets to a positive value. I'm concerned that may cause issues that I'm not considering.



Any assistance would be greatly appreciated.



UPDATE: Unfortunately, all the solutions provided were throwing errors on our signage system. I suspect it is running some limited version of Javascript, but thats beyond me. However, the different solutions were extremely helpful just in getting me to think of another approach. I think I've finally come on one, as this seems to be working. I'm going to let it run over the holiday and check it on Monday. Thanks again!



var shuttleOrange = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47", "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49", "15:25", "15:51", "16:17", "16:57", "17:37", "18:17"];

var hFirst = shuttleOrange[0].slice(0,2);
var mFirst = shuttleOrange[0].slice(3,5);
var hLast = shuttleOrange[shuttleOrange.length-1].slice(0,2);
var mLast = shuttleOrange[shuttleOrange.length-1].slice(3,5);

var theTime = new Date();
var runFirst = new Date();
var runLast = new Date();

runFirst.setHours(hFirst,mFirst,0);
runLast.setHours(hLast,mLast,0);


if ((runFirst - theTime) >= (30*60*1000)) {
return "The first Orange Shuttle will depart PCN at " + shuttleOrange[0] + "."
} else if (theTime >= runLast) {
return "Orange Shuttle Service has ended for the day."
} else {


for(var i=0, l=shuttleOrange.length; i<l; i++)
{
var h = shuttleOrange[i].slice(0,2);
var m = shuttleOrange[i].slice(3,5);
var departPCN = new Date();

departPCN.setHours(h,m,0);
shuttleOrange[i] = departPCN;
}


for(var i=shuttleOrange.length-1; i--;)
{

//var theTime = new Date();


if (shuttleOrange[i] < theTime) shuttleOrange.splice(i,1)
}


var timeRem = Math.floor((shuttleOrange[0] - theTime)/1000/60);


if (timeRem >= 2) {
return "Departing in " + timeRem + " minutes."
} else if (timeRem > 0 && timeRem < 2) {
return "Departing in " + timeRem + " minute."
} else {

return "Departing now."
}
}









share|improve this question





























    0















    For our digital signage system, I'd like to show how long until the next bus departs. I've built the array that holds all the times and successfully (maybe not elegantly or efficiently) gotten it to change all that to show how much time is remaining (positive or negative) until each listed departure.



    I need a nudge in the right direction as to how to determine which bus is next based on the current time. If there is a bus in 7 minutes, I only need to display that one, not the next one that leaves in 20 minutes.



    I was thinking perhaps a for loop that looks at the array of remaining times and stops the first time it gets to a positive value. I'm concerned that may cause issues that I'm not considering.



    Any assistance would be greatly appreciated.



    UPDATE: Unfortunately, all the solutions provided were throwing errors on our signage system. I suspect it is running some limited version of Javascript, but thats beyond me. However, the different solutions were extremely helpful just in getting me to think of another approach. I think I've finally come on one, as this seems to be working. I'm going to let it run over the holiday and check it on Monday. Thanks again!



    var shuttleOrange = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47", "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49", "15:25", "15:51", "16:17", "16:57", "17:37", "18:17"];

    var hFirst = shuttleOrange[0].slice(0,2);
    var mFirst = shuttleOrange[0].slice(3,5);
    var hLast = shuttleOrange[shuttleOrange.length-1].slice(0,2);
    var mLast = shuttleOrange[shuttleOrange.length-1].slice(3,5);

    var theTime = new Date();
    var runFirst = new Date();
    var runLast = new Date();

    runFirst.setHours(hFirst,mFirst,0);
    runLast.setHours(hLast,mLast,0);


    if ((runFirst - theTime) >= (30*60*1000)) {
    return "The first Orange Shuttle will depart PCN at " + shuttleOrange[0] + "."
    } else if (theTime >= runLast) {
    return "Orange Shuttle Service has ended for the day."
    } else {


    for(var i=0, l=shuttleOrange.length; i<l; i++)
    {
    var h = shuttleOrange[i].slice(0,2);
    var m = shuttleOrange[i].slice(3,5);
    var departPCN = new Date();

    departPCN.setHours(h,m,0);
    shuttleOrange[i] = departPCN;
    }


    for(var i=shuttleOrange.length-1; i--;)
    {

    //var theTime = new Date();


    if (shuttleOrange[i] < theTime) shuttleOrange.splice(i,1)
    }


    var timeRem = Math.floor((shuttleOrange[0] - theTime)/1000/60);


    if (timeRem >= 2) {
    return "Departing in " + timeRem + " minutes."
    } else if (timeRem > 0 && timeRem < 2) {
    return "Departing in " + timeRem + " minute."
    } else {

    return "Departing now."
    }
    }









    share|improve this question



























      0












      0








      0








      For our digital signage system, I'd like to show how long until the next bus departs. I've built the array that holds all the times and successfully (maybe not elegantly or efficiently) gotten it to change all that to show how much time is remaining (positive or negative) until each listed departure.



      I need a nudge in the right direction as to how to determine which bus is next based on the current time. If there is a bus in 7 minutes, I only need to display that one, not the next one that leaves in 20 minutes.



      I was thinking perhaps a for loop that looks at the array of remaining times and stops the first time it gets to a positive value. I'm concerned that may cause issues that I'm not considering.



      Any assistance would be greatly appreciated.



      UPDATE: Unfortunately, all the solutions provided were throwing errors on our signage system. I suspect it is running some limited version of Javascript, but thats beyond me. However, the different solutions were extremely helpful just in getting me to think of another approach. I think I've finally come on one, as this seems to be working. I'm going to let it run over the holiday and check it on Monday. Thanks again!



      var shuttleOrange = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47", "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49", "15:25", "15:51", "16:17", "16:57", "17:37", "18:17"];

      var hFirst = shuttleOrange[0].slice(0,2);
      var mFirst = shuttleOrange[0].slice(3,5);
      var hLast = shuttleOrange[shuttleOrange.length-1].slice(0,2);
      var mLast = shuttleOrange[shuttleOrange.length-1].slice(3,5);

      var theTime = new Date();
      var runFirst = new Date();
      var runLast = new Date();

      runFirst.setHours(hFirst,mFirst,0);
      runLast.setHours(hLast,mLast,0);


      if ((runFirst - theTime) >= (30*60*1000)) {
      return "The first Orange Shuttle will depart PCN at " + shuttleOrange[0] + "."
      } else if (theTime >= runLast) {
      return "Orange Shuttle Service has ended for the day."
      } else {


      for(var i=0, l=shuttleOrange.length; i<l; i++)
      {
      var h = shuttleOrange[i].slice(0,2);
      var m = shuttleOrange[i].slice(3,5);
      var departPCN = new Date();

      departPCN.setHours(h,m,0);
      shuttleOrange[i] = departPCN;
      }


      for(var i=shuttleOrange.length-1; i--;)
      {

      //var theTime = new Date();


      if (shuttleOrange[i] < theTime) shuttleOrange.splice(i,1)
      }


      var timeRem = Math.floor((shuttleOrange[0] - theTime)/1000/60);


      if (timeRem >= 2) {
      return "Departing in " + timeRem + " minutes."
      } else if (timeRem > 0 && timeRem < 2) {
      return "Departing in " + timeRem + " minute."
      } else {

      return "Departing now."
      }
      }









      share|improve this question
















      For our digital signage system, I'd like to show how long until the next bus departs. I've built the array that holds all the times and successfully (maybe not elegantly or efficiently) gotten it to change all that to show how much time is remaining (positive or negative) until each listed departure.



      I need a nudge in the right direction as to how to determine which bus is next based on the current time. If there is a bus in 7 minutes, I only need to display that one, not the next one that leaves in 20 minutes.



      I was thinking perhaps a for loop that looks at the array of remaining times and stops the first time it gets to a positive value. I'm concerned that may cause issues that I'm not considering.



      Any assistance would be greatly appreciated.



      UPDATE: Unfortunately, all the solutions provided were throwing errors on our signage system. I suspect it is running some limited version of Javascript, but thats beyond me. However, the different solutions were extremely helpful just in getting me to think of another approach. I think I've finally come on one, as this seems to be working. I'm going to let it run over the holiday and check it on Monday. Thanks again!



      var shuttleOrange = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47", "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49", "15:25", "15:51", "16:17", "16:57", "17:37", "18:17"];

      var hFirst = shuttleOrange[0].slice(0,2);
      var mFirst = shuttleOrange[0].slice(3,5);
      var hLast = shuttleOrange[shuttleOrange.length-1].slice(0,2);
      var mLast = shuttleOrange[shuttleOrange.length-1].slice(3,5);

      var theTime = new Date();
      var runFirst = new Date();
      var runLast = new Date();

      runFirst.setHours(hFirst,mFirst,0);
      runLast.setHours(hLast,mLast,0);


      if ((runFirst - theTime) >= (30*60*1000)) {
      return "The first Orange Shuttle will depart PCN at " + shuttleOrange[0] + "."
      } else if (theTime >= runLast) {
      return "Orange Shuttle Service has ended for the day."
      } else {


      for(var i=0, l=shuttleOrange.length; i<l; i++)
      {
      var h = shuttleOrange[i].slice(0,2);
      var m = shuttleOrange[i].slice(3,5);
      var departPCN = new Date();

      departPCN.setHours(h,m,0);
      shuttleOrange[i] = departPCN;
      }


      for(var i=shuttleOrange.length-1; i--;)
      {

      //var theTime = new Date();


      if (shuttleOrange[i] < theTime) shuttleOrange.splice(i,1)
      }


      var timeRem = Math.floor((shuttleOrange[0] - theTime)/1000/60);


      if (timeRem >= 2) {
      return "Departing in " + timeRem + " minutes."
      } else if (timeRem > 0 && timeRem < 2) {
      return "Departing in " + timeRem + " minute."
      } else {

      return "Departing now."
      }
      }






      javascript date time






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Nov 21 '18 at 20:19







      Mike

















      asked Nov 14 '18 at 21:21









      MikeMike

      32




      32
























          2 Answers
          2






          active

          oldest

          votes


















          0














          You only need to search once to find the index of the next scheduled time. Then as each time elapses, increment the index to get the next time. Once you're at the end of the array, start again.



          A sample is below, most code is setup and helpers. It creates a dummy schedule for every two minutes from 5 minutes ago, then updates the message. Of course you can get a lot more sophisticated, e.g. show a warning when it's in the last few minutes, etc. But this shows the general idea.






          window.addEventListener('DOMContentLoaded', function() {

          // Return time formatted as HH:mm
          function getHHmm(d) {
          return `${('0'+d.getHours()).slice(-2)}:${('0'+d.getMinutes()).slice(-2)}`;
          }

          var sched = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47",
          "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49",
          "15:25", "15:51", "16:17", "16:57", "17:37", "18:17","21:09"];
          var msg = '';
          var msgEl = document.getElementById('alertInfo');
          var time = getHHmm(new Date());
          var index = 0;

          // Set index to next scheduled time, stop if reach end of schedule
          while (time.localeCompare(sched[index]) > 0 && index < sched.length) {
          ++index;
          }

          function showNextBus(){
          var time = getHHmm(new Date());
          var schedTime;

          // If run out of times, next scheduled time must be the first one tomorrow
          if (index == sched.length && time.localeCompare(sched[index - 1]) > 0) {
          msg = `Current time: ${time} - Next bus: ${sched[0]} tomorrow`;

          // Otherwise, show next scheduled time today
          } else {
          // Fix index if rolled over a day
          index = index % sched.length;
          schedTime = sched[index];
          msg = `Current time: ${time} - Next bus: ${schedTime}`;

          if (schedTime == time) msg += ' DEPARTING!!';

          // Increment index if gone past this scheduled time
          index += time.localeCompare(schedTime) > 0? 1 : 0;
          }

          msgEl.textContent = msg;

          // Update message each second
          // The could be smarter, using setInterval to schedule running at say 95%
          // of the time to the next sched time, but never more than twice a second
          setInterval(showNextBus, 1000);
          }

          showNextBus();
          }, false);

          <div id="alertInfo"></div>





          Edit



          You're right, I didn't allow for the case where the current time is after all the scheduled times on the first running. Fixed. I also changed all the string comparisons to use localeCompare, which I think is more robust. Hopefully the comments are sufficient.






          share|improve this answer


























          • Man, I spent almost two days hacking mine together and you two pulled something out of your back pockets in no time. Much appreciated! I'll take a look at these now, though I have no clue what they are doing...

            – Mike
            Nov 15 '18 at 14:29











          • Unfortunately, both of those solutions are giving me errors. I'm suspecting it may have something to do with the way our digital signage is using Javascript, but I don't know. However, both of you have given me a different tack to try. I'm attempting to go through the schedule times and remove any that are before the current time. That should result in an array where the first index is the next bus. Then, I need only do the math on that element. Maybe?

            – Mike
            Nov 15 '18 at 21:24













          • Okay, I don't know how to add code to a comment. So, I edited the initial post with the new attempt.

            – Mike
            Nov 15 '18 at 21:30











          • As it is, it does eliminate some of the earlier times, but not all of them. At this time, 4:30pm, it eliminates the first 9 items.

            – Mike
            Nov 15 '18 at 21:32





















          0














          I have used filter for all shuttle left after the right time and calculated how much time left for the first one.






          var shuttleOrange = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47", "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49", "15:25", "15:51", "16:17", "16:57", "17:37", "18:17"];

          var d = new Date();
          var h = d.getHours();
          var m = d.getMinutes();

          var remainShuttle = shuttleOrange.filter(bus => bus.substring(0,2) > h || (bus.substring(0,2) == h && bus.substring(3,5) > m));

          var leftMinutes = (parseInt(remainShuttle[0].substring(0,2))*60 + parseInt(remainShuttle[0].substring(3,5)) - (parseInt(h) *60 + parseInt(m)));

          console.log(parseInt(leftMinutes / 60) + " hours and " + leftMinutes % 60 +" minutes left for next shuttle");








          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53308915%2fdetermining-time-remaining-until-bus-departs%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            You only need to search once to find the index of the next scheduled time. Then as each time elapses, increment the index to get the next time. Once you're at the end of the array, start again.



            A sample is below, most code is setup and helpers. It creates a dummy schedule for every two minutes from 5 minutes ago, then updates the message. Of course you can get a lot more sophisticated, e.g. show a warning when it's in the last few minutes, etc. But this shows the general idea.






            window.addEventListener('DOMContentLoaded', function() {

            // Return time formatted as HH:mm
            function getHHmm(d) {
            return `${('0'+d.getHours()).slice(-2)}:${('0'+d.getMinutes()).slice(-2)}`;
            }

            var sched = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47",
            "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49",
            "15:25", "15:51", "16:17", "16:57", "17:37", "18:17","21:09"];
            var msg = '';
            var msgEl = document.getElementById('alertInfo');
            var time = getHHmm(new Date());
            var index = 0;

            // Set index to next scheduled time, stop if reach end of schedule
            while (time.localeCompare(sched[index]) > 0 && index < sched.length) {
            ++index;
            }

            function showNextBus(){
            var time = getHHmm(new Date());
            var schedTime;

            // If run out of times, next scheduled time must be the first one tomorrow
            if (index == sched.length && time.localeCompare(sched[index - 1]) > 0) {
            msg = `Current time: ${time} - Next bus: ${sched[0]} tomorrow`;

            // Otherwise, show next scheduled time today
            } else {
            // Fix index if rolled over a day
            index = index % sched.length;
            schedTime = sched[index];
            msg = `Current time: ${time} - Next bus: ${schedTime}`;

            if (schedTime == time) msg += ' DEPARTING!!';

            // Increment index if gone past this scheduled time
            index += time.localeCompare(schedTime) > 0? 1 : 0;
            }

            msgEl.textContent = msg;

            // Update message each second
            // The could be smarter, using setInterval to schedule running at say 95%
            // of the time to the next sched time, but never more than twice a second
            setInterval(showNextBus, 1000);
            }

            showNextBus();
            }, false);

            <div id="alertInfo"></div>





            Edit



            You're right, I didn't allow for the case where the current time is after all the scheduled times on the first running. Fixed. I also changed all the string comparisons to use localeCompare, which I think is more robust. Hopefully the comments are sufficient.






            share|improve this answer


























            • Man, I spent almost two days hacking mine together and you two pulled something out of your back pockets in no time. Much appreciated! I'll take a look at these now, though I have no clue what they are doing...

              – Mike
              Nov 15 '18 at 14:29











            • Unfortunately, both of those solutions are giving me errors. I'm suspecting it may have something to do with the way our digital signage is using Javascript, but I don't know. However, both of you have given me a different tack to try. I'm attempting to go through the schedule times and remove any that are before the current time. That should result in an array where the first index is the next bus. Then, I need only do the math on that element. Maybe?

              – Mike
              Nov 15 '18 at 21:24













            • Okay, I don't know how to add code to a comment. So, I edited the initial post with the new attempt.

              – Mike
              Nov 15 '18 at 21:30











            • As it is, it does eliminate some of the earlier times, but not all of them. At this time, 4:30pm, it eliminates the first 9 items.

              – Mike
              Nov 15 '18 at 21:32


















            0














            You only need to search once to find the index of the next scheduled time. Then as each time elapses, increment the index to get the next time. Once you're at the end of the array, start again.



            A sample is below, most code is setup and helpers. It creates a dummy schedule for every two minutes from 5 minutes ago, then updates the message. Of course you can get a lot more sophisticated, e.g. show a warning when it's in the last few minutes, etc. But this shows the general idea.






            window.addEventListener('DOMContentLoaded', function() {

            // Return time formatted as HH:mm
            function getHHmm(d) {
            return `${('0'+d.getHours()).slice(-2)}:${('0'+d.getMinutes()).slice(-2)}`;
            }

            var sched = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47",
            "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49",
            "15:25", "15:51", "16:17", "16:57", "17:37", "18:17","21:09"];
            var msg = '';
            var msgEl = document.getElementById('alertInfo');
            var time = getHHmm(new Date());
            var index = 0;

            // Set index to next scheduled time, stop if reach end of schedule
            while (time.localeCompare(sched[index]) > 0 && index < sched.length) {
            ++index;
            }

            function showNextBus(){
            var time = getHHmm(new Date());
            var schedTime;

            // If run out of times, next scheduled time must be the first one tomorrow
            if (index == sched.length && time.localeCompare(sched[index - 1]) > 0) {
            msg = `Current time: ${time} - Next bus: ${sched[0]} tomorrow`;

            // Otherwise, show next scheduled time today
            } else {
            // Fix index if rolled over a day
            index = index % sched.length;
            schedTime = sched[index];
            msg = `Current time: ${time} - Next bus: ${schedTime}`;

            if (schedTime == time) msg += ' DEPARTING!!';

            // Increment index if gone past this scheduled time
            index += time.localeCompare(schedTime) > 0? 1 : 0;
            }

            msgEl.textContent = msg;

            // Update message each second
            // The could be smarter, using setInterval to schedule running at say 95%
            // of the time to the next sched time, but never more than twice a second
            setInterval(showNextBus, 1000);
            }

            showNextBus();
            }, false);

            <div id="alertInfo"></div>





            Edit



            You're right, I didn't allow for the case where the current time is after all the scheduled times on the first running. Fixed. I also changed all the string comparisons to use localeCompare, which I think is more robust. Hopefully the comments are sufficient.






            share|improve this answer


























            • Man, I spent almost two days hacking mine together and you two pulled something out of your back pockets in no time. Much appreciated! I'll take a look at these now, though I have no clue what they are doing...

              – Mike
              Nov 15 '18 at 14:29











            • Unfortunately, both of those solutions are giving me errors. I'm suspecting it may have something to do with the way our digital signage is using Javascript, but I don't know. However, both of you have given me a different tack to try. I'm attempting to go through the schedule times and remove any that are before the current time. That should result in an array where the first index is the next bus. Then, I need only do the math on that element. Maybe?

              – Mike
              Nov 15 '18 at 21:24













            • Okay, I don't know how to add code to a comment. So, I edited the initial post with the new attempt.

              – Mike
              Nov 15 '18 at 21:30











            • As it is, it does eliminate some of the earlier times, but not all of them. At this time, 4:30pm, it eliminates the first 9 items.

              – Mike
              Nov 15 '18 at 21:32
















            0












            0








            0







            You only need to search once to find the index of the next scheduled time. Then as each time elapses, increment the index to get the next time. Once you're at the end of the array, start again.



            A sample is below, most code is setup and helpers. It creates a dummy schedule for every two minutes from 5 minutes ago, then updates the message. Of course you can get a lot more sophisticated, e.g. show a warning when it's in the last few minutes, etc. But this shows the general idea.






            window.addEventListener('DOMContentLoaded', function() {

            // Return time formatted as HH:mm
            function getHHmm(d) {
            return `${('0'+d.getHours()).slice(-2)}:${('0'+d.getMinutes()).slice(-2)}`;
            }

            var sched = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47",
            "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49",
            "15:25", "15:51", "16:17", "16:57", "17:37", "18:17","21:09"];
            var msg = '';
            var msgEl = document.getElementById('alertInfo');
            var time = getHHmm(new Date());
            var index = 0;

            // Set index to next scheduled time, stop if reach end of schedule
            while (time.localeCompare(sched[index]) > 0 && index < sched.length) {
            ++index;
            }

            function showNextBus(){
            var time = getHHmm(new Date());
            var schedTime;

            // If run out of times, next scheduled time must be the first one tomorrow
            if (index == sched.length && time.localeCompare(sched[index - 1]) > 0) {
            msg = `Current time: ${time} - Next bus: ${sched[0]} tomorrow`;

            // Otherwise, show next scheduled time today
            } else {
            // Fix index if rolled over a day
            index = index % sched.length;
            schedTime = sched[index];
            msg = `Current time: ${time} - Next bus: ${schedTime}`;

            if (schedTime == time) msg += ' DEPARTING!!';

            // Increment index if gone past this scheduled time
            index += time.localeCompare(schedTime) > 0? 1 : 0;
            }

            msgEl.textContent = msg;

            // Update message each second
            // The could be smarter, using setInterval to schedule running at say 95%
            // of the time to the next sched time, but never more than twice a second
            setInterval(showNextBus, 1000);
            }

            showNextBus();
            }, false);

            <div id="alertInfo"></div>





            Edit



            You're right, I didn't allow for the case where the current time is after all the scheduled times on the first running. Fixed. I also changed all the string comparisons to use localeCompare, which I think is more robust. Hopefully the comments are sufficient.






            share|improve this answer















            You only need to search once to find the index of the next scheduled time. Then as each time elapses, increment the index to get the next time. Once you're at the end of the array, start again.



            A sample is below, most code is setup and helpers. It creates a dummy schedule for every two minutes from 5 minutes ago, then updates the message. Of course you can get a lot more sophisticated, e.g. show a warning when it's in the last few minutes, etc. But this shows the general idea.






            window.addEventListener('DOMContentLoaded', function() {

            // Return time formatted as HH:mm
            function getHHmm(d) {
            return `${('0'+d.getHours()).slice(-2)}:${('0'+d.getMinutes()).slice(-2)}`;
            }

            var sched = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47",
            "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49",
            "15:25", "15:51", "16:17", "16:57", "17:37", "18:17","21:09"];
            var msg = '';
            var msgEl = document.getElementById('alertInfo');
            var time = getHHmm(new Date());
            var index = 0;

            // Set index to next scheduled time, stop if reach end of schedule
            while (time.localeCompare(sched[index]) > 0 && index < sched.length) {
            ++index;
            }

            function showNextBus(){
            var time = getHHmm(new Date());
            var schedTime;

            // If run out of times, next scheduled time must be the first one tomorrow
            if (index == sched.length && time.localeCompare(sched[index - 1]) > 0) {
            msg = `Current time: ${time} - Next bus: ${sched[0]} tomorrow`;

            // Otherwise, show next scheduled time today
            } else {
            // Fix index if rolled over a day
            index = index % sched.length;
            schedTime = sched[index];
            msg = `Current time: ${time} - Next bus: ${schedTime}`;

            if (schedTime == time) msg += ' DEPARTING!!';

            // Increment index if gone past this scheduled time
            index += time.localeCompare(schedTime) > 0? 1 : 0;
            }

            msgEl.textContent = msg;

            // Update message each second
            // The could be smarter, using setInterval to schedule running at say 95%
            // of the time to the next sched time, but never more than twice a second
            setInterval(showNextBus, 1000);
            }

            showNextBus();
            }, false);

            <div id="alertInfo"></div>





            Edit



            You're right, I didn't allow for the case where the current time is after all the scheduled times on the first running. Fixed. I also changed all the string comparisons to use localeCompare, which I think is more robust. Hopefully the comments are sufficient.






            window.addEventListener('DOMContentLoaded', function() {

            // Return time formatted as HH:mm
            function getHHmm(d) {
            return `${('0'+d.getHours()).slice(-2)}:${('0'+d.getMinutes()).slice(-2)}`;
            }

            var sched = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47",
            "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49",
            "15:25", "15:51", "16:17", "16:57", "17:37", "18:17","21:09"];
            var msg = '';
            var msgEl = document.getElementById('alertInfo');
            var time = getHHmm(new Date());
            var index = 0;

            // Set index to next scheduled time, stop if reach end of schedule
            while (time.localeCompare(sched[index]) > 0 && index < sched.length) {
            ++index;
            }

            function showNextBus(){
            var time = getHHmm(new Date());
            var schedTime;

            // If run out of times, next scheduled time must be the first one tomorrow
            if (index == sched.length && time.localeCompare(sched[index - 1]) > 0) {
            msg = `Current time: ${time} - Next bus: ${sched[0]} tomorrow`;

            // Otherwise, show next scheduled time today
            } else {
            // Fix index if rolled over a day
            index = index % sched.length;
            schedTime = sched[index];
            msg = `Current time: ${time} - Next bus: ${schedTime}`;

            if (schedTime == time) msg += ' DEPARTING!!';

            // Increment index if gone past this scheduled time
            index += time.localeCompare(schedTime) > 0? 1 : 0;
            }

            msgEl.textContent = msg;

            // Update message each second
            // The could be smarter, using setInterval to schedule running at say 95%
            // of the time to the next sched time, but never more than twice a second
            setInterval(showNextBus, 1000);
            }

            showNextBus();
            }, false);

            <div id="alertInfo"></div>





            window.addEventListener('DOMContentLoaded', function() {

            // Return time formatted as HH:mm
            function getHHmm(d) {
            return `${('0'+d.getHours()).slice(-2)}:${('0'+d.getMinutes()).slice(-2)}`;
            }

            var sched = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47",
            "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49",
            "15:25", "15:51", "16:17", "16:57", "17:37", "18:17","21:09"];
            var msg = '';
            var msgEl = document.getElementById('alertInfo');
            var time = getHHmm(new Date());
            var index = 0;

            // Set index to next scheduled time, stop if reach end of schedule
            while (time.localeCompare(sched[index]) > 0 && index < sched.length) {
            ++index;
            }

            function showNextBus(){
            var time = getHHmm(new Date());
            var schedTime;

            // If run out of times, next scheduled time must be the first one tomorrow
            if (index == sched.length && time.localeCompare(sched[index - 1]) > 0) {
            msg = `Current time: ${time} - Next bus: ${sched[0]} tomorrow`;

            // Otherwise, show next scheduled time today
            } else {
            // Fix index if rolled over a day
            index = index % sched.length;
            schedTime = sched[index];
            msg = `Current time: ${time} - Next bus: ${schedTime}`;

            if (schedTime == time) msg += ' DEPARTING!!';

            // Increment index if gone past this scheduled time
            index += time.localeCompare(schedTime) > 0? 1 : 0;
            }

            msgEl.textContent = msg;

            // Update message each second
            // The could be smarter, using setInterval to schedule running at say 95%
            // of the time to the next sched time, but never more than twice a second
            setInterval(showNextBus, 1000);
            }

            showNextBus();
            }, false);

            <div id="alertInfo"></div>






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Nov 16 '18 at 11:18

























            answered Nov 15 '18 at 3:53









            RobGRobG

            98.4k19108146




            98.4k19108146













            • Man, I spent almost two days hacking mine together and you two pulled something out of your back pockets in no time. Much appreciated! I'll take a look at these now, though I have no clue what they are doing...

              – Mike
              Nov 15 '18 at 14:29











            • Unfortunately, both of those solutions are giving me errors. I'm suspecting it may have something to do with the way our digital signage is using Javascript, but I don't know. However, both of you have given me a different tack to try. I'm attempting to go through the schedule times and remove any that are before the current time. That should result in an array where the first index is the next bus. Then, I need only do the math on that element. Maybe?

              – Mike
              Nov 15 '18 at 21:24













            • Okay, I don't know how to add code to a comment. So, I edited the initial post with the new attempt.

              – Mike
              Nov 15 '18 at 21:30











            • As it is, it does eliminate some of the earlier times, but not all of them. At this time, 4:30pm, it eliminates the first 9 items.

              – Mike
              Nov 15 '18 at 21:32





















            • Man, I spent almost two days hacking mine together and you two pulled something out of your back pockets in no time. Much appreciated! I'll take a look at these now, though I have no clue what they are doing...

              – Mike
              Nov 15 '18 at 14:29











            • Unfortunately, both of those solutions are giving me errors. I'm suspecting it may have something to do with the way our digital signage is using Javascript, but I don't know. However, both of you have given me a different tack to try. I'm attempting to go through the schedule times and remove any that are before the current time. That should result in an array where the first index is the next bus. Then, I need only do the math on that element. Maybe?

              – Mike
              Nov 15 '18 at 21:24













            • Okay, I don't know how to add code to a comment. So, I edited the initial post with the new attempt.

              – Mike
              Nov 15 '18 at 21:30











            • As it is, it does eliminate some of the earlier times, but not all of them. At this time, 4:30pm, it eliminates the first 9 items.

              – Mike
              Nov 15 '18 at 21:32



















            Man, I spent almost two days hacking mine together and you two pulled something out of your back pockets in no time. Much appreciated! I'll take a look at these now, though I have no clue what they are doing...

            – Mike
            Nov 15 '18 at 14:29





            Man, I spent almost two days hacking mine together and you two pulled something out of your back pockets in no time. Much appreciated! I'll take a look at these now, though I have no clue what they are doing...

            – Mike
            Nov 15 '18 at 14:29













            Unfortunately, both of those solutions are giving me errors. I'm suspecting it may have something to do with the way our digital signage is using Javascript, but I don't know. However, both of you have given me a different tack to try. I'm attempting to go through the schedule times and remove any that are before the current time. That should result in an array where the first index is the next bus. Then, I need only do the math on that element. Maybe?

            – Mike
            Nov 15 '18 at 21:24







            Unfortunately, both of those solutions are giving me errors. I'm suspecting it may have something to do with the way our digital signage is using Javascript, but I don't know. However, both of you have given me a different tack to try. I'm attempting to go through the schedule times and remove any that are before the current time. That should result in an array where the first index is the next bus. Then, I need only do the math on that element. Maybe?

            – Mike
            Nov 15 '18 at 21:24















            Okay, I don't know how to add code to a comment. So, I edited the initial post with the new attempt.

            – Mike
            Nov 15 '18 at 21:30





            Okay, I don't know how to add code to a comment. So, I edited the initial post with the new attempt.

            – Mike
            Nov 15 '18 at 21:30













            As it is, it does eliminate some of the earlier times, but not all of them. At this time, 4:30pm, it eliminates the first 9 items.

            – Mike
            Nov 15 '18 at 21:32







            As it is, it does eliminate some of the earlier times, but not all of them. At this time, 4:30pm, it eliminates the first 9 items.

            – Mike
            Nov 15 '18 at 21:32















            0














            I have used filter for all shuttle left after the right time and calculated how much time left for the first one.






            var shuttleOrange = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47", "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49", "15:25", "15:51", "16:17", "16:57", "17:37", "18:17"];

            var d = new Date();
            var h = d.getHours();
            var m = d.getMinutes();

            var remainShuttle = shuttleOrange.filter(bus => bus.substring(0,2) > h || (bus.substring(0,2) == h && bus.substring(3,5) > m));

            var leftMinutes = (parseInt(remainShuttle[0].substring(0,2))*60 + parseInt(remainShuttle[0].substring(3,5)) - (parseInt(h) *60 + parseInt(m)));

            console.log(parseInt(leftMinutes / 60) + " hours and " + leftMinutes % 60 +" minutes left for next shuttle");








            share|improve this answer




























              0














              I have used filter for all shuttle left after the right time and calculated how much time left for the first one.






              var shuttleOrange = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47", "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49", "15:25", "15:51", "16:17", "16:57", "17:37", "18:17"];

              var d = new Date();
              var h = d.getHours();
              var m = d.getMinutes();

              var remainShuttle = shuttleOrange.filter(bus => bus.substring(0,2) > h || (bus.substring(0,2) == h && bus.substring(3,5) > m));

              var leftMinutes = (parseInt(remainShuttle[0].substring(0,2))*60 + parseInt(remainShuttle[0].substring(3,5)) - (parseInt(h) *60 + parseInt(m)));

              console.log(parseInt(leftMinutes / 60) + " hours and " + leftMinutes % 60 +" minutes left for next shuttle");








              share|improve this answer


























                0












                0








                0







                I have used filter for all shuttle left after the right time and calculated how much time left for the first one.






                var shuttleOrange = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47", "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49", "15:25", "15:51", "16:17", "16:57", "17:37", "18:17"];

                var d = new Date();
                var h = d.getHours();
                var m = d.getMinutes();

                var remainShuttle = shuttleOrange.filter(bus => bus.substring(0,2) > h || (bus.substring(0,2) == h && bus.substring(3,5) > m));

                var leftMinutes = (parseInt(remainShuttle[0].substring(0,2))*60 + parseInt(remainShuttle[0].substring(3,5)) - (parseInt(h) *60 + parseInt(m)));

                console.log(parseInt(leftMinutes / 60) + " hours and " + leftMinutes % 60 +" minutes left for next shuttle");








                share|improve this answer













                I have used filter for all shuttle left after the right time and calculated how much time left for the first one.






                var shuttleOrange = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47", "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49", "15:25", "15:51", "16:17", "16:57", "17:37", "18:17"];

                var d = new Date();
                var h = d.getHours();
                var m = d.getMinutes();

                var remainShuttle = shuttleOrange.filter(bus => bus.substring(0,2) > h || (bus.substring(0,2) == h && bus.substring(3,5) > m));

                var leftMinutes = (parseInt(remainShuttle[0].substring(0,2))*60 + parseInt(remainShuttle[0].substring(3,5)) - (parseInt(h) *60 + parseInt(m)));

                console.log(parseInt(leftMinutes / 60) + " hours and " + leftMinutes % 60 +" minutes left for next shuttle");








                var shuttleOrange = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47", "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49", "15:25", "15:51", "16:17", "16:57", "17:37", "18:17"];

                var d = new Date();
                var h = d.getHours();
                var m = d.getMinutes();

                var remainShuttle = shuttleOrange.filter(bus => bus.substring(0,2) > h || (bus.substring(0,2) == h && bus.substring(3,5) > m));

                var leftMinutes = (parseInt(remainShuttle[0].substring(0,2))*60 + parseInt(remainShuttle[0].substring(3,5)) - (parseInt(h) *60 + parseInt(m)));

                console.log(parseInt(leftMinutes / 60) + " hours and " + leftMinutes % 60 +" minutes left for next shuttle");





                var shuttleOrange = ["09:01", "09:37", "10:03", "10:29", "10:55", "11:21", "11:47", "12:13", "12:39", "13:05", "13:31", "13:57", "14:23", "14:49", "15:25", "15:51", "16:17", "16:57", "17:37", "18:17"];

                var d = new Date();
                var h = d.getHours();
                var m = d.getMinutes();

                var remainShuttle = shuttleOrange.filter(bus => bus.substring(0,2) > h || (bus.substring(0,2) == h && bus.substring(3,5) > m));

                var leftMinutes = (parseInt(remainShuttle[0].substring(0,2))*60 + parseInt(remainShuttle[0].substring(3,5)) - (parseInt(h) *60 + parseInt(m)));

                console.log(parseInt(leftMinutes / 60) + " hours and " + leftMinutes % 60 +" minutes left for next shuttle");






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Nov 14 '18 at 22:11









                krezuskrezus

                649518




                649518






























                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53308915%2fdetermining-time-remaining-until-bus-departs%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Florida Star v. B. J. F.

                    Error while running script in elastic search , gateway timeout

                    Adding quotations to stringified JSON object values