Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

compare two date using javascript

I have two date in which one is dd-mm-yyyy hh:mm format and another in dd-mm-yyyy (D1) format fristly i split the dd-mm-yyyy hh:mm format date to get dd-mm-yyyy (D2) format only then i compare the date D2 and D1 like

var D1 = new Date(); 
var D2 = new Date(); 
// D1 = 03-05-2014  this date take as an example
// D2 = 28-04-2014 00:00  this date take as an example
// D1 and D2 are taken by input fields.
    split the D2 date

dat = D2.split(' ');
D2 = dat[0];
//finally D2 is 28-04-2014
if(D2<=D1)
{
  echo "ok";
}
else{
  echo "something is wrong";
}

I am always getting the else part, is this because i split the date from 28-04-2014 00:00 to 28-04-2014 ?

like image 661
Mr. Tomar Avatar asked May 03 '14 10:05

Mr. Tomar


3 Answers

dateFirst = D1.split('-');
dateSecond = D2.split('-');
var value = new Date(dateFirst[2], dateFirst[1], dateFirst[0]); //Year, Month, Date
var current = new Date(dateSecond[2], dateSecond[1], dateSecond[0]);

than use the if condition

if(D2<=D1)
{
console.log('ok');
}
else
{
console.log('something is wrong');
}
like image 153
harendar Avatar answered Oct 01 '22 12:10

harendar


This is you need actually

var D1 = "03-05-2014";
var D2 = "28-04-2014 00:00";

if ((new Date(D1).getTime()) >= (new Date(D2).getTime())) {
    alert('correct');
} else {
    alert('wrong');
}

WORKING DEMO

like image 33
underscore Avatar answered Oct 01 '22 11:10

underscore


That is a string comparison you are doing, not a date comparison

In terms of strings... 2 is greater than 0... That's why you always hit the "something is wrong" statement

EDIT: This is an explanation of what went wrong // Creates a date variable var D1 = new Date();

// Creates another date variable
var D2 = new Date();

// Converts this date variable into a string
D1 = 03-05-2014 

// This is too is converted into a string
D2 = 28-04-2014 00:00

    dat = D2.split(' ');
D2 = dat[0];

//finally D2 is 28-04-2014  <-- true, but it is a string
if(D2<=D1){    //   <-- At this point you are doing a string comparison

        echo "ok";

} else {

    echo "something is wrong";

}

EDIT: This is a possible solution. . .

Instead of that, do this

var D1 = new Date();
var D2 = new Date();

if(D2.getTime() <= D1.getTime()){
    echo "ok";
} else {
    echo "something is wrong";
}

EDIT: If you are getting it from an input field, then do this

// Make sure you dates are in the format YYYY-MM-DD.
    // In other words, 28-04-2014 00:00 becomes 2014-04-28 00:00
// Javascript Date only accepts the ISO format by default
var D1 = new Date( $('#input1#').val() );
var D2 = new Date( $('#input2#').val() );

    if(D2.getTime() <= D1.getTime()){
    echo "ok";
} else {
    echo "something is wrong";
}
like image 22
Abimbola Esuruoso Avatar answered Oct 01 '22 13:10

Abimbola Esuruoso