Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare dates with javascript [duplicate]

I have two dates in javascript:

var first = '2012-11-21';
var second = '2012-11-03';

i would like make:

 if(first > second){
   //...
 }

how is the best way for this, without external library?

like image 385
Paul Jeggor Avatar asked Jun 23 '12 13:06

Paul Jeggor


3 Answers

if( (new Date(first).getTime() > new Date(second).getTime()))
{
    ----------------------------------
}
like image 197
Arthur Neves Avatar answered Oct 09 '22 07:10

Arthur Neves


If your dates are strings in a strict yyyy-mm-dd format as shown in the question then your code will work as is without converting to date objects or numbers:

if(first > second){

...will do a lexographic (i.e., alphanumeric "dictionary order") string comparison - which will compare the first characters of each string, then the second characters of each string, etc. Which will give the result you want...

like image 22
nnnnnn Avatar answered Oct 09 '22 08:10

nnnnnn


You can do this way, it will work fine:

var date1 = new Date('2013-07-30');
var date2 = new Date('2013-07-30');

if(date1 === date2){ console.log("both are equal");}  //it does not work 
==>undefined  //result
if(+date1 === +date2){ console.log("both are equal");} //do it this way! 
//(use + prefix for a variable that holds a date value)
==> both are equal //result

Note :- don't forget to use a + prefix

like image 9
Balachandar1887229 Avatar answered Oct 09 '22 08:10

Balachandar1887229