December 7, 2012, 9:17 am - James Farrer
I had a client that needed a script to see if a date entered on a form was in the future. I had some code that did it but it was in need of some clean up. I reworked it a little bit and thought I'd post it here for future reference
/**
* Get the number of days difference between the date given and the current date
*
* Example
* If todays date is 2012-12-07 then the following would return 2
* dayDiff("2012-12-09");
*
* Parameter
* date_string - date in the format of yyyy-mm-dd
* Returns
* Number of days between date_string and the current date. Positive numbers are in the future.
*/
function dayDiff(date_string){
// Accepts dates in the form of yyyy-mm-dd, change these next few lines if a different format is needed
var yearfield=date_string.split("-")[0];
var monthfield=date_string.split("-")[1];
var dayfield=date_string.split("-")[2];
// Build the date object
var dayobj = new Date(yearfield, monthfield-1, dayfield);
var val_to_return = false;
// Get today's date and time
var t = new Date();
// We only want the day so create a new date without the time component
var today = new Date(t.getFullYear(), t.getMonth(), t.getDate());
// Calculate the difference
var diff = dayobj - today;
// Convert the difference to days
diff = diff/1000/60/60/24;
return diff;
}