I'm trying to setup a countdown which takes a date and time entered in a backend dashboard and displays a countdown on the frontend, the countdown should be to that date across timezones, if someone is in a different timezone it should still countdown the days, hrs, mins, secs to the same time.
I am really struggling with whether the new Date() should have Z included or not, whether to use an offset and some DST concerns based on my scenario. I've tried each and got the results below, one works but I'm not 100% sure why.
In summary: How can I get this countdown script to countdown to the same date/time no matter what timezone the visitor is in. I think the answer might be in relation to being able to include the timezone offset at the time entered in the dashboard in new Date()?
See the code comments below.
function countdown() {
var countdown = document.getElementById( 'countdown' );
var countdownDate = new Date( '2023-06-22T22:00Z' ).getTime(); // This could be any date/time entered via backend dashboard which has 2 inputs one to select a date (stored in Y-m-d format) and one to select a time (stored in 00:00 format), this is output via <?php echo $date; ?>T<php echo $time; ?>Z, the backend dashboard has a general timezone setting which if needed can return in formats of Europe/London, UTC, +/-0:00, etc
// If Z not on the end
// if in UK countdown is correct
// if in Pago Pago the countdown is to the local 10pm - I want the countdown to be to the same across timezones
// If Z is on the end
// if in UK countdown incorrect as 1 hour out
// if in Pago Pago countdown incorrect as 1 hour out
// If Z not on the end and I replace with +01:00
// if in UK countdown is correct
// if in Pago Pago the countdown is correct (same countdown as UK)
// BUT i'm unsure exactly why +01:00 seems to work I think this is because I am currently in a +01:00 time zone and I entered the dates in the admin area when timezone was +01:00, it seems like this would cause issues in future relating to DST
// Note that I am testing Pago Pago using Chrome DevTools > Sensors > Location
var x = setInterval( function() {
var now = new Date().getTime();
var distance = countdownDate - now;
if ( distance < 0 ) {
clearInterval( x );
countdown.remove();
} else {
var days = Math.floor( distance / ( 1000 * 60 * 60 * 24 ) );
var hours = Math.floor( ( distance % ( 1000 * 60 * 60 * 24 ) ) / ( 1000 * 60 * 60 ) );
var minutes = Math.floor( ( distance % ( 1000 * 60 * 60 ) ) / ( 1000 * 60 ) );
var seconds = Math.floor( ( distance % ( 1000 * 60 ) ) / 1000 );
var text = '';
text += days + ' days ';
text += hours + ' hours ';
text += minutes + ' minutes ';
text += seconds + ' seconds ';
countdown.innerHTML = text;
}
}, 1000 );
}
countdown();
<div id="countdown"></div>