我想用 toIsoString 函式格式化我的日期,但函式回傳 -1 天如何解決?event.value 格式是Tue Apr 19 2022 00:00:00 GMT 0400 (Armenia Standard Time)
console.log(new Date(event.value).toISOString().slice(0,10))
在控制臺中,我得到了這個,你2022-04-18怎么能看到結果是 -1 天
startDateChange(event: any): void{
this.firstDayOfMonth = event;
console.log(new Date(event.value).toISOString().slice(0, 10));
}
uj5u.com熱心網友回復:
這是因為您的時區設定。當您在時區作業時,toISOString總是會回傳。這基本上撤回了 4 小時,導致前一天的 20:00 小時。 0000 0400
您可以嘗試通過向日期添加 Z 將時區偏移設定為 0 來解決此問題,如第二個示例所示。
第三個示例是一種安全的方法,但如果需要,您需要在 0 前面加上前綴。
另一種選擇是使用像 Moment.js 這樣的日期庫,盡管時刻已被棄用(我不確定最好的選擇是什么,這取決于你)。
// Your example (this might work for some people that are in the 0000 timezone)
console.log(new Date('2021-03-03T00:00:00').toISOString().slice(0,10));
// Second example
console.log(new Date('2021-03-03T00:00:00z').toISOString().slice(0,10));
// Third example
const date = new Date('2021-03-03T00:00:00');
const year = date.getFullYear();
const month = date.getMonth() 1;
const day = date.getDate();
console.log(`${year}-${month}-${day}`);
uj5u.com熱心網友回復:
您可以使用https://day.js.org/
代碼:
const dateString = 'Tue Apr 19 2022 00:00:00 GMT 0400 (Armenia Standard Time)'
const date1 = dayjs(dateString).format('YYYY-MM-DD')
console.log(date1)
const date2 = dayjs(dateString).format('YYYY-M-D')
console.log(date2)
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.11.0/dayjs.min.js"></script>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/456822.html
標籤:javascript 日期
