Tuesday, November 5, 2013

JavaScript Date Compare


I quite often need to compare a date selected on a form to the current date. Usually because I wish to prohibit the form user from selecting a due date in the past. I came up with this JavaScript function to accomplish this check:
/*
Function:     DateGEToday
Parameters:   dateToCompare, a date string to compare against
Returns:      True, if dateToCompare is greater than or equal to today
*/
function DateGEToday(dateToCompare) {
    // By default, set our compare result to false
    var result = false;
    // Convert the passed date to a date data type
    var comp = new Date(dateToCompare);
    // Create a data data type for the current date/time
    var now = new Date();
    // Create a new due date that does not include the time
    var dueDate = new Date(comp.getFullYear(), comp.getMonth(), comp.getDate());
    // Create a new current date that does not include the time
    var today = new Date(now.getFullYear(), now.GetMonth(), now.getDate());
    // Compare the two date only variables
    if (dueDate >= today) {
        result = true;
    }
    // Return the boolean result
    return result;
}

Caveat: I am a JavaScript novice, so I welcome constructive comments. I don't doubt this code could be reduced and/or simplified, but it works and it makes sense to me.

The call to this script in a form validation checker might look like this...
var dueDate = document.getElementById('<%= dtcDateTime.Controls[0].ClientID %>');
if (!DateGEToday(dueDate.value)) {
    document.getElementById('<%= dtcDateTime.Controls[0].ClientID %>').focus();
    alert('Due date must be today or future date!');
}

No comments:

Post a Comment