Sudarshan Kalebere Sudarshan Kalebere - 1 month ago 9
Javascript Question

how to compare selected date is greater than todays date in moment

I am using angularjs and moment library, I have

start_date
object contains several dates, once user clicks proceed I am checking each date to check whether it is valid date i,e which is greater than today or equal to today, else I am throwing error.

Here is my code

$scope.checkDateTime = function(){
angular.forEach($scope.orders.start_date,function(s){
console.log('data'+s);
if (moment(s).format('DD-MM-YYYY') < moment().format('DD-MM-YYYY')) {
swal({
title: "Please select a valid date.",
text: "Please select valid start date.",
confirmButtonClass: "btn btn-primary add-prod-btn",
imageUrl: 'images/vmy-sub.png'
})
return false;
}
}
}


EDIT
When I am consoling the value of s I am getting 27-10-2016, when I use moment(s, 'DD-MM-YYYY') I am getting 1477506600000. So I think value I am getting is not string, but when I directly compare it with todays date using moment it says invalid date, I am confused. Any help please.

Answer

As stated in my first comment you can simply use isBefore or isSameOrBefore.

Since your input is a string, you can parse into moment object and then use moment methods.

Your condition will be:

moment(s, 'DD-MM-YYYY').isBefore(moment())