gpt4 book ai didi

javascript - 以字符串格式提供 moment 时出现 ISO 格式弃用警告

转载 作者:行者123 更新时间:2023-12-03 08:45:27 25 4
gpt4 key购买 nike

const DATE_FORMAT = "YYYY-MM-DD";
const endDate = "2020-05-05T00:00:00.000Z" (dynamic value from service)
const appValidDate = moment(endDate).subtract(1, "days").format(DATE_FORMAT);
const currentDate = moment().startOf("day").format(DATE_FORMAT);
const validDate = moment(currentDate).isSameOrBefore(appValidDate);

我一直在尝试使用 moment 来比较两个日期。运行应用程序时,我收到以下弃用警告。

Deprecation warning: value provided is not in a recognized RFC2822 or ISO format. moment construction falls back to js Date(), which is not reliable across all browsers and versions. Non RFC2822/ISO date formats are discouraged and will be removed in an upcoming major release. Please refer to http://momentjs.com/guides/#/warnings/js-date/ for more info.
Arguments:
[0] _isAMomentObject: true, _isUTC: false, _useUTC: false, _l: undefined, _i: Invalid date, _f: undefined, _strict: undefined, _locale: [object Object]
Error:

找到一些有用的 stackoverflow 链接:Moment.js deprecation warning when comparing two dates

但仍然无法删除弃用警告。

所以根据文档,需要采用字符串+格式,所以我这样做了:

const DATE_FORMAT = "YYYY-MM-DD";
const endDate = "2020-05-05T00:00:00.000Z" (dynamic value from service)
const appValidDate = moment(endDate).subtract(1, "days").format(DATE_FORMAT);
const currentDate = moment().startOf("day").format(DATE_FORMAT);
const validDate = moment(currentDate, DATE_FORMAT).isSameOrBefore(appValidDate);

但问题是我们无法将 endDate 转换为字符串然后减去天数。如果我这样通过,就会出现 Moment 错误。

任何人都可以帮我找到一个合适的解决方案吗?任何帮助将不胜感激。

最佳答案

如上面评论中所述,使用 moment 实例进行日期比较。

.format() 返回的值是一个字符串,根据所选的格式(可能还有您的区域设置)可能会触发您看到的警告。

当您想要显示值时,请使用.format()

const DATE_FORMAT = "YYYY-MM-DD";
const endDate = "2020-05-05T00:00:00.000Z" //(dynamic value from service)
const appValidDate = moment(endDate).subtract(1, "days");
const currentDate = moment().startOf("day");
// or for a UTC "start of day"
// const currentDate = moment.utc().startOf('day')
const validDate = currentDate.isSameOrBefore(appValidDate);

console.log('appValidDate:', appValidDate.format(DATE_FORMAT))
console.log('currentDate:', currentDate.format(DATE_FORMAT))
console.log('validDate:', validDate)
<script src="https://momentjs.com/downloads/moment.js"></script>

关于javascript - 以字符串格式提供 moment 时出现 ISO 格式弃用警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61626454/

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