Problem in comparing dates in Javascript

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
eshban
Forum Contributor
Posts: 184
Joined: Mon Sep 05, 2005 1:38 am

Problem in comparing dates in Javascript

Post 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
User avatar
kaszu
Forum Regular
Posts: 749
Joined: Wed Jul 19, 2006 7:29 am

Re: Problem in comparing dates in Javascript

Post 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) {
Post Reply