Link to home
Create AccountLog in
Avatar of tia_kamakshi
tia_kamakshiFlag for United Arab Emirates

asked on

Validating dates in javascript

Hi Experts,

I wanted to compare dates in javascript. I have a dates in format

// 18-Sep-2013
// 15-Oct-2013

if(document.getElementById("car_eventDate_from").value >= document.getElementById("car_eventDate_return").value)   
{

}

WHERE

Value for document.getElementById("car_eventDate_from").value = 18-Sep-2013
Value for document.getElementById("car_eventDate_return").value = 15-Oct-2013

Open in new window



Above date validation works fine if we take dates in july, aug

but if we take dates in sep and oct it fails.

Please help making above condition works with calculating dates.

Thanks & Regards
ASKER CERTIFIED SOLUTION
Avatar of Amar Bardoliwala
Amar Bardoliwala
Flag of India image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of Rob
Taking what has been posted... see here for a working example

http://jsfiddle.net/rjurd/RQQAa/

html:
<div id='car_eventDate_from'>18-Sep-2013</div>
<div id='car_eventDate_return'>15-Oct-2013</div>
<div id='result'></div>

Open in new window


javascript:
var date_from = customParse(document.getElementById('car_eventDate_from').innerHTML);
var date_return = customParse(document.getElementById('car_eventDate_return').innerHTML);

if(date_from >= date_return)   
{
document.getElementById('result').innerHTML = 'from is greater';
}
else {
document.getElementById('result').innerHTML = 'return is greater';
}
function customParse(str) {
    var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
        'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
        n = months.length,
        re = /(\d{2})-([a-z]{3})-(\d{4})/i,
        matches;

    while (n--) {
        months[months[n]] = n;
    } // map month names to their index :)

    matches = str.match(re); // extract date parts from string

    return new Date(matches[3], months[matches[2]], matches[1]);
}

Open in new window