I have a countdown timer which transfers time from H:i:s to long version using this script:
function parseTime() {
var timeLeftStr;
var timeLeft = 0;
timeLeftStr = document.getElementById("timeleft").innerHTML;
timeLeftStr.replace(/(\d+):(\d+):(\d+)/, function () {
for (var i = 1; i < arguments.length - 2; i++) {
// Convert to ms
timeLeft += arguments[i] * Math.pow(60, 3 - i) * 1000;
}
});
countdown(new Date(timeLeft));
}
function countdown(timeLeft) {
var hours = timeLeft.getHours();
var minutes = timeLeft.getMinutes();
var seconds = timeLeft.getSeconds();
if (timeLeft.valueOf() == 0) {
document.getElementById("timeleft").innerHTML = "0 seconds";
window.location = 'home.php?pageid=' + getURLParam("pageid");
return false;
} else {
document.getElementById("timeleft").innerHTML =
(hours == 0 ? "" : hours + (hours == 1 ? " hour" : " hours")) +
(minutes == 0 ? "" : (hours ? (seconds ? ", " : " and ") : " ") + minutes + (minutes == 1 ? " minute" : " minutes")) +
(seconds == 0 ? "" : (hours || minutes ? " and " : "") + seconds + (seconds == 1 ? " second" : " seconds"));
setTimeout(function () { countdown(new Date(timeLeft - 1000)); }, 1000);
}
}
window.onload = parseTime;
The error is that a user of mine who lives in Australia keeps getting the wrong "hour" The original timer would say something like "23:45:05" but when the countdown timer starts it says "10 hours, 45 minutes and 5 seconds" rather than 23 hours.
Any idea why this could be happening? Thank you.
Im not that great at JS, this was created by a friend.
Worked it out in the end.
well, this happens because javascript gets the current date and time from the client: so when it's 23 o'clock in your country, in another part of the world a client who make a request to the page will show a different hour (and probably day)
if you want to show the same time everywhere you should get the server
date and time so you're sure it's the same for every client or you should get the local timezone and apply an offset.
You could take a look a this similar discussion: Javascript countdown using absolute timezone?