Reputation: 31
I am using _i
in momentjs with if condition but it is not giving expected output.
Here is my code:
var output = "07-14-2017";
var selectedDates = "06-15-2018";
if(moment(output)._i <= moment(selectedDates)._i)
{
console.log(output date is less than or equal selected date);
}
else
{
console.log(output date is greater than selected date);
}
Here my output date is of 2017 and selecteddates
is of 2018, still it is giving me an output of 'output date is greater than selected date'. It should give me an output 'output date is less than or equal selected date'.
I have given all jQuery and momentjs files references properly.
Upvotes: 0
Views: 2356
Reputation: 31482
There are 2 issue with your code:
moment(String)
a string that is neither in RFC2822 or ISO 8601 recognized format, so your code gives Deprecation warning. You have to use moment(String, String)
instead._i
that as Internal Properties guide states:
[...] the values of
_d
and any other properties prefixed with_
should not be used for any purpose.
To compare moment objects you can use isSameOrBefore
, isAfter
, isBefore
and the others methods listed in the Query section of the docs.
Here a working sample:
var output = "07-14-2017";
var selectedDates = "06-15-2018";
if(moment(output, 'MM-DD-YYYY').isSameOrBefore(moment(selectedDates, 'MM-DD-YYYY')))
{
console.log("output date is less than or equal selected date");
}
else
{
console.log("output date is greater than selected date");
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
Upvotes: 2
Reputation: 1253
_i returns string which is not correct and also you should not use it as per @Andreas comments. You can use below code gives correct comparison.
moment(selectedDates).isAfter(output);
Upvotes: 0
Reputation: 2042
I just tested your code and it works in Chrome 59, however it threw the following warning:
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.
It's possible that your issues are with your browser's javascript engine's implementation of Date(), as hinted in the warning above.
I would recommend you reformat your dates to a more moment-friendly format and try again.
Upvotes: 0