23

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;
}
1
  • Are you sure your date picker is not returning actual javascript Date objects? If it is then you can just compare them. Commented Sep 7, 2011 at 14:00

3 Answers 3

36

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]);
}
Sign up to request clarification or add additional context in comments.

4 Comments

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.
it should be return new Date(parts[2], parts[1] +1, parts[0]);
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 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
14

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.

1 Comment

Much better solution than the one accepted as answer
8
function process(date){
   var parts = date.split("/");
   var date = new Date(parts[1] + "/" + parts[0] + "/" + parts[2]);
   return date.getTime();
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.