gpt4 book ai didi

javascript new Date 和 UTC 日期给出相同的 UTC 时间

转载 作者:行者123 更新时间:2023-11-28 03:07:27 25 4
gpt4 key购买 nike

我有以下 JavaSCript 代码:

function getDate() {
return new Date().toJSON();
}

function getUtcDate() {
var date = new Date();
var now_utc = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
return new Date(now_utc).toJSON();
}

两者都返回相同的日期时间,我期望 getDate() 返回我的本地时间..它并不像您在图像中看到的那样

enter image description here我上传了jsfiddle here

对正在发生的事情有什么建议吗?

最佳答案

function getDate() {
return new Date().toLocaleString();
}

function getDateOffset() {
return new Date().getTimezoneOffset() / 60;
}

function getUtcDate() {
return new Date().toUTCString();
}


console.log('Local Date = '+ getDate());
console.log('local TimeZone Offset = '+ getDateOffset())
console.log('UTC Date = '+ getUtcDate());

<小时/>

已更新

var date = moment.utc().format();
console.log(date, "UTC");

var local = moment.utc(date).local().format();// add parameter to format to remove Timezone Offset
console.log(local, "UTC to Local + TimeZone Offset");

console.log('---------------------------------------------');
// you can use .format() from momentjs to return any format you want
var formattedDate = moment.utc().format('YYYY-MM-DD HH:mm:ss a');
console.log(formattedDate);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

关于javascript new Date 和 UTC 日期给出相同的 UTC 时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60474268/

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