0

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
}
LovePoke
  • 45
  • 1
  • 8

2 Answers2

1

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);
}
Master Yoda
  • 4,334
  • 10
  • 43
  • 77
  • In fact if my months are in a different language than English it will not work so I will have to translate either in English or with number... – LovePoke Dec 06 '17 at 13:45
  • @LovePoke What exactly is your question? As it stands from your current question my answer is will work just fine. If its in another language then localization needs to be taken into account and thats a different ball game. Why not just commit to one specific date format? – Master Yoda Dec 06 '17 at 13:48
  • yeah sorry I didn't take into account that the localization would be a problem ^^". Then yeah I have to convert to a specific format then use getTime() maybe. In fact I have to extract multiple date that is in the format I said earlier, and compare each with the current date. – LovePoke Dec 06 '17 at 13:52
  • Then I would stick with one date format and convert/compare your other dates to that date format. – Master Yoda Dec 06 '17 at 14:40
  • Using the built-in parser for non–standard strings is **strongly** advised against. It's just a very bad idea, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) In particular, 05/12/2017 will likely not be parsed as d/m/y as required by the OP. – RobG Dec 07 '17 at 12:32
0

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
}
Jeremy Jackson
  • 2,247
  • 15
  • 24
  • Using the built-in parser is not a good idea, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Dec 07 '17 at 12:34