我試圖讓我的資料保持在巴西的時區,但是每次我嘗試更改它時,當我給控制臺時它會顯示正確的日期,但是一旦我將它發送到我的后端,日期就會完全改變時區,我只需要獲取今天的日期,但是由于有時區,晚上 9 點當天更改為第二天,我做錯了什么?我在這里嘗試了這段代碼。
let date = new Date();
//this simulates the time after 21:00, just change the 15 to the number of hours needed so that the time is like after 21:00 to test (now is 8 am in Brazil)
date.setHours(date.getHours() 15);
date = date.toISOString().split('T')[0];
$('#date').append(date.toLocaleString("pt-BR"));
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<div id="date">
</div>
uj5u.com熱心網友回復:
Date.toISOString()將為您提供UTC時間作為 ISO 字串。
如果您想獲取本地日期作為 ISO 字串,這很容易做到,使用Date.getFullYear(),Date.getMonth()和Date.getDate()值。
我們創建一個包含 [年、月、日] 值的陣列,然后使用String.padStart()和String.join()創建 ISO 日期。
這將在當地時區給出正確的一年中的一天。
function getIsoDate(date) {
const ymd = [ date.getFullYear(), date.getMonth() 1, date.getDate() ];
return ymd.map(s => (s '').padStart(2, '0')).join('-');
}
console.log(getIsoDate(new Date()));
console.log(getIsoDate(new Date('2022-10-19T22:30:00')));
console.log(getIsoDate(new Date('2022-10-19T00:00:00')));
.as-console-wrapper { max-height: 100% !important; }
一個簡單的 hack 也可以使用Date.toLocaleDateString(),將 locale 引數設定為 'sv',這是因為這種語言使用 ISO 格式顯示日期。
function getIsoDate(date) {
return date.toLocaleDateString('sv');
}
console.log(getIsoDate(new Date()));
console.log(getIsoDate(new Date('2022-10-19T21:30:00')));
.as-console-wrapper { max-height: 100% !important; }
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/522217.html
上一篇:如何從歷史表中跟蹤有效和有效到
