Search code examples
javascriptjquerycountdown

Multiple Countdown with timezone


I need to use Multiple Countdown in a single page with timezone.. I found Final Countdown

I found the code i needed. but couldnt get it to work in the right timezone.

    $(function(){
 $('[data-countdown]').each(function() {
   var $this = $(this), finalDate = $(this).data('countdown');
   $this.countdown(finalDate, function(event) {
     $this.html(event.strftime('%H:%M:%S'));
   });
 });
});

This is for the multiple countdowns which works fine..

This one is for timezone with a single countdown.

var nextYear = moment.tz("2020-05-29 00:00", "America/Sao_Paulo");

$('#clock').countdown(nextYear.toDate(), function(event) {
  $(this).html(event.strftime('%D days %H:%M:%S'));
});

How can i get the first one work with proper timezone.. thanks so much


Solution

  • Just use the moment timezone function to pass the date with timezone to each countdown.

    This is what you are looking for?

    $(function(){
        $('[data-countdown]').each(function() {
            var $this = $(this), finalDate = $(this).data('countdown');
            $this.countdown(moment.tz(finalDate, "America/Sao_Paulo").toDate(), function(event) {
                $this.html(event.strftime('%H:%M:%S'));
            });
        });
    });
    

    To get the user local timezone you can try

    console.log(Intl.DateTimeFormat().resolvedOptions().timeZone); // America/Sao_Paulo
    //or with moment
    console.log(moment.tz.guess()) // America/Sao_Paulo
    

    Make sure you import moment cdn libraries

    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.26.0/moment.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.31/moment-timezone.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.31/moment-timezone-with-data.min.js"></script>