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

Vis*_*hnu 2 javascript datetime node.js momentjs

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);
Run Code Online (Sandbox Code Playgroud)

我一直在尝试使用 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:
Run Code Online (Sandbox Code Playgroud)

找到了一些有用的 stackoverflow 链接:比较两个日期时的 Moment.js 弃用警告

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

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

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);
Run Code Online (Sandbox Code Playgroud)

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

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

Phi*_*hil 5

正如上面评论中所解释的,使用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)
Run Code Online (Sandbox Code Playgroud)
<script src="https://momentjs.com/downloads/moment.js"></script>
Run Code Online (Sandbox Code Playgroud)