我没有看到任何符合我的用例的线程。我正在尝试比较两个日期,看看它们是否匹配。如果不这样做,那么我会显示一条错误消息。两个日期的日期格式均为 '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/