gpt4 book ai didi

javascript - 在 Javascript 日期中使用 UTC 时区

转载 作者:行者123 更新时间:2023-12-03 01:32:46 28 4
gpt4 key购买 nike

这是我目前拥有的代码,但我正在努力将其转换为 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com