Nifel
Nifel

Reputation: 177

Using moment.js to countdown to a specific day and hour

I am using moment.js for providing time and dates of specific locations all around the world. Now I want to have a countdown timer where it is always counting down to the next monday AND a specific hour that monday.

I have already seen some solutions that are close (but no cigar), but the solutions usually have a specific date in mind.

I just want it to have an hourly countdown to the next upcoming monday at a specific hour. So for example, the output can be "Time until opening: 2 days, 6 hours", which will be from the current local time that I already have from moment.js.

Upvotes: 1

Views: 3443

Answers (2)

waseel almahri
waseel almahri

Reputation: 504

You can use this code I personally use it. You can change the number of seconds as needed, for example, on the day 12960000 seconds

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <script src="https://momentjs.com/downloads/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="countdown"></div>
    <title>Static Template</title>
  </head>
  <body>
   <script>

    var countDownDate = moment().add(12960000, 'seconds');

      var x = setInterval(function() {
        diff = countDownDate.diff(moment());
    
        if (diff <= 0) {
          clearInterval(x);
           // If the count down is finished, write some text 
          $('.countdown').text("EXPIRED");
        } else
          $('.countdown').text(moment.utc(diff).format("HH:mm:ss"));

      }, 1000);
     </script>
  </body>
</html>

enter code here

Upvotes: 1

Evgenii Malikov
Evgenii Malikov

Reputation: 437

You could use the latest moment.js fromNow function.

Here is example if opening date is next monday, 10:00

var openingDate = moment().day(1).hour(10).minute(0).second(0);
var fromNow = openingDate.fromNow();
console.log(fromNow);

will output in 19 hours

Upvotes: 1

Related Questions