odd_duck odd_duck - 10 months ago 60
Javascript Question

Javascript Countdown Timer in GMT/UTC

I have the following javascript code for a countdown timer:

var end = new Date('10/26/2016 4:00 PM');

var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;

function showRemaining() {
var now = new Date();
var distance = end - now;
if (distance < 0) {

document.getElementById('countdown').innerHTML = 'EXPIRED!';

var days = Math.floor(distance / _day);
var hours = Math.floor((distance % _day) / _hour);
var minutes = Math.floor((distance % _hour) / _minute);
var seconds = Math.floor((distance % _minute) / _second);

document.getElementById('countdown').innerHTML = minutes + 'mins ' + seconds + 'secs';

timer = setInterval(showRemaining, 1000);

This works but the problem is I need the countdown timer to work on GMT/UTC time as all my times on the site / server are all stored in that way.

At the moment this countdown timer is using the users local time for the
setting. This script will be accessed worldwide so i cannot use local timezones and it must be in the GMT/UTC format.

i.e as of the time of posting this the current GMT time is 13:17 but if I access the script over in the UK the local time is 14:17 so the countdown is out by 1 hour.

I know javascript has the


method but when I try and call this on

function showRemaining() {
var now = new Date().toUTCString();

It results in this output:

NaNmins NaNsecs

jsfiddle is here => https://jsfiddle.net/pzbz35q1/1/

Answer Source

I have used something similar to the following before:

var now = new Date();
var nowUTC = new Date(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate(), now.getUTCHours(), now.getUTCMinutes(), now.getUTCSeconds());
var distance = end - nowUTC;

The .toUTCString() will place a string of the current UTC date/time in the variable, so any calculations based off it will fail (as it's trying to calculate a number from a string).