gpt4 book ai didi

node.js - Moment.js 将日期设置为落后 1 天

转载 作者:搜寻专家 更新时间:2023-10-31 23:34:09 25 4
gpt4 key购买 nike

我正在使用 2.22.1 来格式化日期。

当我输入来自日期选择器的日期时,moment 会将日期倒退一天。例如,当我尝试按以下方式格式化日期时:

示例 1:

const day = new Date(value).getDate();
const month = new Date(value).getMonth();
const fullYear = new Date(value).getFullYear();
console.log('day', day); // 7
console.log('month', month); // 5
console.log('fullYear', fullYear); //2018

格式化函数:

moment.utc(new Date(month + ' ' + day + ' ' + fullYear), 'MM-DD-YYYY').format('DD-MM-YY')

输出:06-05-18

预计:07-05-18

示例 2:

输入:2018 年 5 月 31 日星期四 00:00:00 GMT+0100(GMT 夏令时)

格式化函数:

moment.utc(new Date(value)).format('DD-MM-YY')

输出:30-05-18预计:31-05-18

最佳答案

moment.utc 会将输入转换为世界时。
您正在使用基于 GMT +1 的输入运行 new Date(...)

如果你仔细想想,这是完全有道理的。
您的输出是 30-05-18,因为前一天是晚上 11 点/23:00。

这(无论如何)实际上会起作用:

moment('05-06-2018', 'MM-DD-YYYY').format('DD-MM-YY')
// alternatively (and preferrably) this:
moment.utc('05-06-2018', 'MM-DD-YYYY').format('DD-MM-YY')

并输出:"06-05-18"

因为在这个例子中非utc版本不接受时间输入。

moment.js 存在的原因之一,就是在你的代码中一起摆脱 Date
(请记住,Date 现在有了显着改进。DateTimeFormat is a game changer)
请阅读 momentjs documentation关于如何正确使用时刻。

编辑:如果你想用这个处理 400000 个日期,我建议使用 RegExp.split.exec.sliceDate 代替。
(我可以理解,因为我用 javascript generatorsService Workers 编写了一个客户端日志解析器用于统计反作弊分析)
我真的建议玩这些东西来增加你的知识。

关于node.js - Moment.js 将日期设置为落后 1 天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50473932/

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