Reputation: 987
I didn't see any SO thread that matches my use case. I'm trying to compare two dates to see if they match or not. If they don't, then I display an error message. The date format for both dates are in 'MM/DD/YYYY'
format, with the only exception being sometimes they might be 'MM/DD/YYYY'
and other times 'M/D/YYYY'
.
I'm able to get it to work but keep getting a deprecated error. I tried using the moment.ISO_8601
argument but still keep getting the deprecated error.
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!");
}
The deprecated error is following:
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.
Is there a clean fix for this?
Upvotes: 1
Views: 1933
Reputation: 31502
Neither 'MM/DD/YYYY'
nor 'M/D/YYYY'
are ISO 8601 compliant format recognized by moment.ISO_8601
See moment(String)
docs to see what are ISO 8601 formats recognized by momentjs. You have to specify 'MM/DD/YYYY'
(or 'M/D/YYYY'
) format instead of using moment.ISO_8601
.
You can use both 'MM/DD/YYYY'
and 'M/D/YYYY'
using moment(String, String[])
. This is required if you are using strict parsing. Please note that:
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.
For example, using ['MM/DD/YYYY', 'MM/DD/YYYY']
, ambigous inputs like 01/10/2017
will always be interpreted as 10th of January.
Here an example that do not has Deprecation warning:
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>
Upvotes: 3
Reputation: 179
I don't actually see that issue.
http://jsfiddle.net/dbkidd/n9s082bj/
Can you reproduce it in the Fiddle?
var start_date = moment().format('MMM DD h:mm A');
var user_start_date = moment().format('MMM DD h:mm A');
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!");
}
Upvotes: 1