22

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;
}
Toni Michel Caubet
  • 19,333
  • 56
  • 202
  • 378
  • Are you sure your date picker is not returning actual javascript `Date` objects? If it is then you can just compare them. – Jamiec Sep 07 '11 at 14:00

3 Answers3

33

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]);
}
InvisibleBacon
  • 3,137
  • 26
  • 27
  • 1
    This approach would work better than the one I posted because I suspect some dates like 1/1/2000 would default to the mm/dd/yyyy format when converted to a date object. +1 for you, sir. – Maxx Sep 07 '11 at 14:07
  • it should be return new Date(parts[2], parts[1] +1, parts[0]); – Kuttan Sujith Jan 27 '12 at 07:52
  • 3
    No, the month component of the javascript date is zero-based. Besides parts[1] + 1 would cast 1 as a string and append it to the end of the parts[1] string.. – InvisibleBacon Jan 27 '12 at 16:49
  • @InvisibleBacon thanks for your answer and +1. Can u plz tell me if it is '25/02/1985' and '4/12/2015 12:00:00 AM ' . Thanks – Zaker Apr 13 '15 at 19:45
12

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.

rony36
  • 3,277
  • 1
  • 30
  • 42
7
function process(date){
   var parts = date.split("/");
   var date = new Date(parts[1] + "/" + parts[0] + "/" + parts[2]);
   return date.getTime();
}
Maxx
  • 3,925
  • 8
  • 33
  • 38