LovePoke
LovePoke

Reputation: 45

Javascript compare two strings of date in specfic format

I want to compare two strings of date. The format is: day month year. (example: 5 april 2017) I want to see if it's superior or not to the current date. (6 december 2017) Is it possible without being too difficult?

d1 = "5 april 2017"
d2 = "5 december 2017"

if (d1<d2){
//do this
}

Upvotes: 0

Views: 41

Answers (2)

Master Yoda
Master Yoda

Reputation: 4402

You need to create date objects from your date strings first.

d1 = "5 april 2017"
d2 = "5 december 2017"
d3 = "05/04/2017";
d4 = "05/12/2017"

compareDates(d1, d2);
compareDates(d2, d1);
compareDates(d3, d4);
compareDates(d4, d3);

function compareDates( date1, date2 )
{
  if( (new Date(date1) > new Date(date2)) )
    console.log('Is ' + date1 + ' greater than ' + date2 + '? '+ '= ' + true);
  else
    console.log('Is ' + date1 + ' greater than ' + date2 + '? '+ '= ' + false);
}

Upvotes: 1

Jeremy Jackson
Jeremy Jackson

Reputation: 2257

For date comparisons, it's usually best to get them in milliseconds or seconds. With JavaScript this can be done by passing the date to a new Date object, then calling the getTime function to get the milliseconds.

var d1 = new Date("5 april 2017").getTime();
var d2 = new Date("5 december 2017").getTime();

if (d1 < d2) {
    //do this
}

Upvotes: 0

Related Questions