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?
if( (new Date(first).getTime() > new Date(second).getTime()))
{
----------------------------------
}
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...
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With