Page 1 of 1

Problem in comparing dates in Javascript

Posted: Mon Oct 05, 2009 7:32 am
by eshban
Hi,

I have a problem related to Javascript.


1) I have a php form in which there two text boxes.

2) User enter date in these text boxes via using a calender control.

3) Dates displayed in the textbox in this format i.e: 05-11-2009

I need to compare the dates of both text boxes, but my code is not working fine.


I think i need to convert these the values of both text boxes to date format, but i am unable to do this.

Can anyone please help in writing the new code.

Thanks

Re: Problem in comparing dates in Javascript

Posted: Mon Oct 05, 2009 12:55 pm
by kaszu
1) Convert date into something, what can be compared, like "YYYY-MM-DD"

Code: Select all

function normalizeDateFormat(date) {
    //Match date components (DD MM YYYY)
    var m = String(date).match(/(\d{2}).(\d{2}).(\d{4})/);
    if (m) {
        //Return YYYY MM DD joined with -
        return [m[3], m[2], m[1]].join('-');
    }
    //Date doesn't match format
    return false;
}
Note: this function doesn't check if date is valid.
2) Compare them

Code: Select all

date1 = normalizeDateFormat(date1);
date2 = normalizeDateFormat(date2);
if (d1>d2) {