在Javascript日期中使用UTC时区

时间:2018-07-06 14:20:00

标签: javascript

这是我目前拥有的代码,但我正在努力将其转换为UTC

var today = Date.UTC(new Date());
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
var H = today.getHours();
var i = today.getMinutes();
var s = today.getSeconds();

if(dd<10) {
    dd = '0'+dd
} 

if(mm<10) {
    mm = '0'+mm
} 

today = yyyy + '-' + mm + '-' + dd + ' ' + H + ':' + i + ':' + s;

关于如何使它以相同的时间戳格式工作的任何想法?谢谢!

1 个答案:

答案 0 :(得分:1)

Date对象始终存储在UTC中-您正在调用的.getXxx()函数会将UTC时间隐式转换为本地时区。

要提取UTC时间中的相关字段,您应该使用.getUTCxxx()系列函数。

//
// returns the date and time in format 'YYYY-MM-DD hh:mm:ss'
//
// will take a `Date` object, or use the current system
// time if none is supplied
//
function UTC_DateTime(date) {
    if (date === undefined) {
         date = new Date();
    }

    function pad2(n) {
        return (n < 10) ? ('0' + n) : n;
    }

    return date.getUTCFullYear() + '-' +
           pad2(date.getUTCMonth() + 1) + '-' +
           pad2(date.getUTCDay()) + ' ' +
           pad2(date.getUTCHours()) + ':' +
           pad2(date.getUTCMinutes()) + ':' +
           pad2(date.getUTCSeconds());
}