这是我目前拥有的代码,但我正在努力将其转换为 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;
关于如何让它以相同的时间戳格式工作有什么想法吗?谢谢!
最佳答案
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());
}
关于javascript - 在 Javascript 日期中使用 UTC 时区,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51212445/