简体   繁体   中英

How to get UTC timezone in javascript and adjust to PDT/PT

I have a countdown timer timer constructed but it's just using getTime(), i'm unsure how to adjust this so it is the correct timezone i want (PDT/PT)

var countdownTimer = setInterval(countdownTick, 1000);

function countdownTick() {
    jQuery('ul.countdown').each(function() {
        var date = jQuery(this).attr('data-date').split('-'); // Create date array from attribute
        var time = jQuery(this).attr('data-time').split('-'); // Create time array from attribute
        for (var i = 0; i < date.length; i++) {
            date[i] = parseInt(date[i]);
        }
        for (var i = 0; i < time.length; i++) {
            time[i] = parseInt(time[i]);
        }
        var today = new Date();
        var theDate = new Date(date[0], (date[1] - 1), date[2], time[0], time[1]);
        if (theDate.getTime() > today.getTime()) { // If the target date is in the future
            countdownCalc(this, theDate, today); // Calculate how much time there is until the target date
        }
    });
}

function countdownCalc(obj, targetDate, currentDate) {
    var oneDay = 1000 * 60 * 60 * 24;
    var oneSecond = 1000;
    var output = (targetDate.getTime() - currentDate.getTime());
    var day = Math.floor(output / oneDay);
    var hour = Math.floor((output - (day * oneDay)) / (1000 * 60 * 60));
    var minute = Math.floor((output - (hour * (1000 * 60 * 60) + (day * oneDay))) / (1000 * 60));
    var second = Math.floor((output - ((minute * 60000) + (hour * 1000 * 60 * 60) + (day * oneDay))) / 1000);
    jQuery(obj).html('<li><span class="countdown-label">DAYS</span><span class="countdown-number">' + day + '</span></li><li><span class="countdown-label">HOURS</span><span class="countdown-number">' + hour + '</span></li><li><span class="countdown-label">MINUTES</span><span class="countdown-number">' + minute + '</span></li><li><span class="countdown-label">SECONDS</span><span class="countdown-number">' + second + '</span></li>');
}

https://jsfiddle.net/4nag4h5v/

Here is where plugins become useful, using moment-timezone.js

We are able to do something is simple as:

let time = Date.now();
moment(time).tz("YOURTIMEZONE").format('x') // get timestamp (in milliseconds

Without using an external library, the simplest way to do it is by using an offset between your local and target timezones:

let today = new Date(),
  localOffset = -(today.getTimezoneOffset()/60),
  targetOffset = -8,
  netOffset = targetOffset - targetOffset;

const d = new Date(new Date().getTime() + netOffset * 3600 * 1000);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM