user2857239
user2857239

Reputation:

Date comparision is failing in javascript

I am comparing 2 dates

1) 2013-12-18

2) 2013-12-4

My code is considering 2013-12-4 greater than 2013-12-18.

Here is my code DEMO: http://jsfiddle.net/tdVGL/

Here is my JavaScript Code:

var date = new Date();
var getFromDate = 
    parseInt(date.getFullYear()) + '-' + 
    parseInt(date.getMonth() + 1) + '-' + 
    parseInt(date.getDate() - 14);
var newDate = new Date();
var newD = parseInt(newDate.getDate());
var newM = parseInt(newDate.getMonth() + 1);
var newY = parseInt(newDate.getFullYear());
var myDate = parseInt(newY) + '-' + parseInt(newM) + '-' + parseInt(newD);
alert(getFromDate);
alert(myDate);
if (getFromDate < myDate) {
    alert("Sorry! You cannot add event on past dates.");
    return false;
} else {
    alert("This is the right day");
}

Upvotes: 0

Views: 65

Answers (3)

Rapha&#235;l Althaus
Rapha&#235;l Althaus

Reputation: 60493

As stated by Sachim, you're just doing comparison on string, not on Date object.

You could simplify your code (working only on Date object)

var myDate     = new Date();                
var getFromDate = new Date(myDate);
getFromDate.setDate(myDate.getDate() -14);

alert(getFromDate);//of course, this is not in the format yyyy-mm-dd
alert(myDate);

if(getFromDate<myDate)
{
    alert("Sorry! You cannot add event on past dates.");
    return false;
}
else
{
     alert("This is the right day");
}

Upvotes: 1

Scary Wombat
Scary Wombat

Reputation: 44854

The objects that you are trying to compare are not dates, they are Strings

var getFromDate = parseInt(date.getFullYear())+'-'+parseInt(date.getMonth()+1)+'-'+parseInt(date.getDate()-14);

You could instantiate new Dates as

new Date(getFromDate) and new Date(myDate)

and then do the compare

Upvotes: 0

Sachin
Sachin

Reputation: 40990

What are you comparing is not the date comparison. Those values are treating as string. Look at this comparison. You need to convert them into a valid Date object for correct date comparison.

if (new Date(getFromDate) < new Date(myDate)) {
   alert("Sorry! You cannot add event on past dates.");
   return false;
}
else {
   alert("This is the right day");
}

Js Fiddle Demo

Upvotes: 2

Related Questions