javascript - 比较两个日期时 Moment.js 弃用警告

标签 javascript momentjs

我没有看到任何符合我的用例的线程。我正在尝试比较两个日期,看看它们是否匹配。如果不这样做,那么我会显示一条错误消息。两个日期的日期格式均为 'MM/DD/YYYY' 格式,唯一的异常(exception)是有时可能为 'MM/DD/YYYY',其他时候则可能为 'MM/DD/YYYY' 'M/D/YYYY'

我能够让它工作,但不断收到已弃用的错误。我尝试使用 moment.ISO_8601 参数,但仍然不断收到已弃用的错误。

if( !moment( start_date, moment.ISO_8601 ).isSame( user_start_date, 
  moment.ISO_8601 ) )
{
    console.log("Both dates must match!");
}
else {
    console.log("Dates match!");
}

已弃用的错误如下:

moment.js:1 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.

<小时/>

有没有一个干净的解决方案?

最佳答案

'MM/DD/YYYY''M/D/YYYY' 均不被 moment.ISO_8601 识别为符合 ISO 8601 的格式。请参阅moment(String)文档以查看 momentjs 识别的 ISO 8601 格式是什么。您必须指定'MM/DD/YYYY'(或'M/D/YYYY')格式,而不是使用moment.ISO_8601

您可以使用 moment(String, String[]) 来使用 'MM/DD/YYYY''M/D/YYYY' 。如果您使用strict parsing,则这是必需的。请注意:

Starting in version 2.3.0, Moment uses some simple heuristics to determine which format to use. In order:

  • Prefer formats resulting in valid dates over invalid ones.
  • Prefer formats that parse more of the string than less and use more of the format than less, i.e. prefer stricter parsing.
  • Prefer formats earlier in the array than later.

例如,使用 ['MM/DD/YYYY', 'MM/DD/YYYY'] 等不明确的输入,如 01/10/2017将始终被解释为 1 月 10 日。

这里是一个没有弃用警告的示例:

var start_date = '11/25/2017';
var user_start_date = '27/12/2017';

if( !moment( start_date, ['MM/DD/YYYY', 'M/D/YYYY']  ).isSame( moment(user_start_date, ['MM/DD/YYYY', 'M/D/YYYY'] )) )
{
    console.log("Both dates must match!");
}
else{
    console.log("Dates match!");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.19.1/moment.min.js"></script>

关于javascript - 比较两个日期时 Moment.js 弃用警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47102999/

相关文章:

javascript - 如何在 Javascript 中读取包含 "https://uswest.xyz.com/@admin?deep_link_id=35&deep_link_type=user"的 URL?

javascript - CET 时区中的日期到用户时区的日期

javascript - 使用 moment.js 将天数添加到区域设置特定日期

javascript - 如果我将 Google 分析代码放在 IF 语句中,它会起作用吗?

javascript - NativeScript 插件在外部 ng2 项目(不是演示)中崩溃

javascript - 如何调试或缩小逻辑错误范围?

javascript - 无法使 moment-timezone.js 工作

javascript - 关于 Node.js 中的全局变量

javascript - 如何从此字符串中获取日期 Wed Dec 11 16 :02:54 CET 2019

javascript - 使用 Moment.js 格式化日期和减去天数