0

I need to compare two dates to check if the selected date is less than today.

//taking current time

    var orignalDateFromAPI = moment();
    var selectedDate = moment(orignalDateFromAPI,"YYYY-MM-DD");

    console.log(selectedDate.format("DD-MM-YYYY"));

    var nativeDate = new Date(selectedDate);
    var parsedDate= moment(nativeDate,"YYYY-MM-DD");

    console.log(parsedDate.format("DD-MM-YYYY"));

    console.log(selectedDate.isSame(parsedDate)); //true
    console.log(selectedDate == parsedDate); //false

Why does the first statement prints true while the second prints false? Is there a better way to check if a date is less than or equal to the other date?

EDIT: I went to the question that was marked as a duplicate but couldn't find any answer related to the moment.js comparison.
I went through moment.js docs and found is same or before. I think this will work fine. Any caveats?

mukesh.kumar
  • 1,100
  • 16
  • 30

1 Answers1

0

== or === cannot be used to compare the object type variables. If you see the type of selectedDate and parsedDate it is of type object (of Moment). So, you cannot use ==. Instead, you must need to use isSame function of MomentJS.

var orignalDateFromAPI = moment();
var selectedDate = moment(orignalDateFromAPI,"YYYY-MM-DD");

console.log(selectedDate.format("DD-MM-YYYY"));

var nativeDate = new Date(selectedDate);
var parsedDate= moment(nativeDate,"YYYY-MM-DD");

console.log(parsedDate.format("DD-MM-YYYY"));

console.log('typeof selectedDate ' + typeof selectedDate);
console.log(selectedDate.isSame(parsedDate)); //true
console.log(selectedDate == parsedDate); //false
<script src="https://momentjs.com/downloads/moment.js"></script>
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62