Search code examples
javascriptdatetimecountdowntimerflipclock

flipclock countdown to specific date in specific timezone without reset


I am trying to create countdown to a specific date using flipclock without the timer resetting or people in different time-zones seeing different numbers. For example, I want to countdown to Feb 20, 12:00am MST.

My problem is that the clock resets when the browser is refreshed after it reaches 0, the time shows negative numbers. If people viewing this clock with the current configuration, it is counting down to Feb 20, 12am in their timezone.

I've started with the countdown to New Years compiled clock and set my date, but not sure how else to address the timezone and reset issues.

var clock;

$(document).ready(function() {

    // Grab the current date
    var currentDate = new Date();

    // Set some date in the future. In this case, it's always Jan 1
    var futureDate = new Date(currentDate.getFullYear() + 0, 1, 20, 0, 0);

    // Calculate the difference in seconds between the future and current date
    var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;

    // Instantiate a coutdown FlipClock
    clock = $('.clock').FlipClock(diff, {
        clockFace: 'DailyCounter',
        countdown: true,
        showSeconds: false,
        callbacks: {
            stop: function() {
                $('.message').html('The clock has stopped!');
            }
        }
    });
});

Solution

  • var clock;
    
    $(document).ready(function() {
    
      // Grab the current date
      var now = new Date();
      var currentDate = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
      currentDate.setHours(currentDate.getHours() - 7);
    
      // Set some date in the future. In this case, it's always Jan 1
      var futureDate = new Date(currentDate.getFullYear() + 0, 1, 20, 0, 0);
    
      // Calculate the difference in seconds between the future and current date
      var diff = futureDate.getTime() / 1000 - currentDate.getTime() / 1000;
    
      // Limit time difference to zero
      if (diff < 0) {
        diff = 0;
      }
    
      // Instantiate a coutdown FlipClock
      clock = $('.clock').FlipClock(diff, {
        clockFace: 'DailyCounter',
        countdown: true,
        showSeconds: false,
        callbacks: {
          stop: function() {
            $('.message').html('The clock has stopped!');
          }
        }
      });
    });
    

    Part solving timezone issue (a bit ugly):

    // Grab the current date
    var now = new Date();
    var currentDate = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(),  now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
    currentDate.setHours(currentDate.getHours() - 7);
    

    Part limiting time difference to not less than zero:

    // Limit time difference to zero
    if (diff < 0) {
      diff = 0;
    }