Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare 2 dates in format DD/MM/YYYY with javascript/jquery

Tags:

Suppose I receive two dates from the datepicker plugin in format DD/MM/YYYY

var date1 = '25/02/1985';  /*february 25th*/
var date2 = '26/02/1985';  /*february 26th*/
/*this dates are results form datepicker*/

if(process(date2) > process(date1)){
   alert(date2 + 'is later than ' + date1);
}

What should this function look like?

function process(date){
   var date;
   // Do something
   return date;
}
like image 718
Toni Michel Caubet Avatar asked Sep 07 '11 13:09

Toni Michel Caubet


People also ask

How do you compare two date objects in JavaScript?

To handle equality comparison, we use the date object alongside the getTime() date method which returns the number of milliseconds. But if we want to compare specific information like day, month, and so on, we can use other date methods like the getDate() , getHours() , getDay() , getMonth() and getYear() .

Can we compare two dates in JavaScript?

In JavaScript, we can compare two dates by converting them into numeric values to correspond to their time. First, we can convert the Date into a numeric value by using the getTime() function. By converting the given dates into numeric values we can directly compare them.

Can you compare two date strings?

To compare two date strings:Pass the strings to the Date() constructor to create 2 Date objects. Compare the output from calling the getTime() method on the dates.


2 Answers

Split on the "/" and use the Date constructor.

function process(date){
   var parts = date.split("/");
   return new Date(parts[2], parts[1] - 1, parts[0]);
}
like image 120
InvisibleBacon Avatar answered Sep 17 '22 13:09

InvisibleBacon


It could be more easier:

var date1 = '25/02/1985';  /*february 25th*/
var date2 = '26/02/1985';  /*february 26th*/

if ($.datepicker.parseDate('dd/mm/yy', date2) > $.datepicker.parseDate('dd/mm/yy', date1)) {

       alert(date2 + 'is later than ' + date1);

}

For more details check this out. Thanks.

like image 26
rony36 Avatar answered Sep 21 '22 13:09

rony36