JS日期格式给出-1天



我想用toIsoString函数格式化我的日期,但函数返回-1天如何修复?事件值格式为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));
}

这是因为您的时区设置。当您在时区中使用+0400时,toISOString始终返回+0000。这基本上撤回了4个小时,导致前一天20:00小时。

您可以尝试通过在日期上添加Z将时区偏移设置为0来解决此问题,如第二个示例所示。

第三个例子是一种安全的方法,但如果需要,您需要在0前面加前缀。

另一种选择是使用Moment.js这样的日期库,尽管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}`);

您可以使用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>

最新更新