Search code examples
javascriptcountdown

Javascript Opening hours countdown


I would like to use an opening time countdown for individual days on my website for a local shop. The shop has opening hours from monday to friday from 09:00 to 18:00 and is open on saturdays from 10:00 to 16:30. I would like to show the users how long the store is open for the day they visit the website. For example a user is on the site on tuesday at 16:30 I want to display something like "Dear customer, our shop is open for another 1,5 hrs.". If the shop is already closed, I would like to display something like "We are currently closed, but you are welcome to visit the store on Monday at 9 o'clock.".

I did a lot of research here and elsewhere, but i just couldn't find a proper solution for this task, so I really hope you could help me.


Solution

  • Make an array mapping your Openning time, with 0 is Sunday

    var openTime = [ {open : -1, close : -1},
                     { open: 9, close : 18 },
                     { open: 9, close : 18 },
                     { open: 9, close : 18 },
                     { open: 9, close : 18 }, 
                     { open: 9, close : 18 },
                     { open: 10, close : 16.5 }
                  ]
    

    then check it when user come to page.

    var current = new Date();
    var day = current.getDay();
    var currentTime = current.getHours() + (current.getMinutes()/60);
    var remainTime = 0;
    if (openTime[day].open >= 0 && openTime[day].open < currentTime && openTime[day].close > currentTime) {
             remainTime= (openTime[day].close  - currentTime).toFixed(2)
    }
    console.log("the shop will close in %s hours", remainTime);