Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set the timezone of a Date object

I'm currently trying to develop a countdown timer page. Here is the countdown timer code:

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("July 01, 2015 22:00:00");

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

    if(diff < 0){
        // Instantiate a countdown FlipClock
        clock = $('.clock').FlipClock(0, {
            clockFace: 'DailyCounter',
            countdown: true
        });
        $('.message').html('Lets Go!!');
        $('.Go').removeAttr("disabled");
        $( "div.first" ).replaceWith( "<i style='color:red'>Lets Go!</i>" );
    }
    else{
        // Instantiate a countdown FlipClock
        clock = $('.clock').FlipClock(diff, {
            clockFace: 'DailyCounter',
            countdown: true,
            callbacks: {
                stop: function() {
                    $('.message').html('Lets Go!!');
                    $('.Go').removeAttr("disabled");
                    $( "div.first" ).replaceWith( "<i style='color:red'>Lets Go!</i>" );
                }
            }
        });
    }

});

The problem is that the countdown time varies per timezone. For example, a user in Australia will have a three-hour-shorter countdown time than that of a user from Malaysia (GMT+8).

How can I standardize/set the initial countdown date's timezone to GMT+8 so that users in different timezones have the same countdown time?

like image 781
Marcus Tan Avatar asked Oct 19 '22 08:10

Marcus Tan


1 Answers

Based on our discussion, this example code works to convert any timezone time into UTC+8 timezone time.

var d = new Date();
d.setTime(d.getTime() + d.getTimezoneOffset() * 60 * 1000 /* convert to UTC */ + (/* UTC+8 */ 8) * 60 * 60 * 1000);
console.log('UTC+8 Time:', d);

Here is a JSFiddle for reference.

Although the console output shows that the timezones of the date objects are not UTC+0800, their date values (year, month, date, etc...) have all been converted into UTC+0800 time.

It is just not possible to edit the actual timezone of date objects, but it is possible to edit their date values to reflect the new timezone, and that is what we are doing here.

like image 158
rgajrawala Avatar answered Oct 21 '22 22:10

rgajrawala