Welcome Login
Blog Photos Links

RSS Feed

Javascript Date Difference (in Days)

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;
}


What's New

There are currently no new items, please check back later.

Archives
2021 (2)
  September (1)
  May (1)
2019 (1)
  August (1)
2018 (3)
  August (1)
  April (1)
  January (1)
2017 (1)
  January (1)
2016 (4)
  December (1)
  November (1)
  May (1)
  January (1)
2015 (1)
  December (1)
2014 (2)
  August (1)
  February (1)
2013 (4)
  October (1)
  July (1)
  June (1)
  April (1)
2012 (11)
  December (2)
  October (3)
  September (1)
  May (1)
  April (1)
  February (2)
  January (1)
2011 (14)
  December (1)
  November (1)
  September (2)
  July (2)
  June (1)
  May (1)
  April (2)
  March (3)
  January (1)
2009 (2)
  October (1)
  June (1)
2008 (1)
  September (1)