SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    SitePoint Member
    Join Date
    Aug 2009
    0 Post(s)
    0 Thread(s)

    Calculating Date Ranges using Javascript?

    I'm fairly new to programming in Javascript and quite frankly find it difficult (an old COBOL programmer). My question is this, are their any functions in Javascript that are similar to the VB.Net "DateDiff" function? If not, are their any free code snippets that will calculate the range of days and/or months between 2 date values?


  2. #2
    SitePoint Enthusiast Anthony.Barnes's Avatar
    Join Date
    Aug 2011
    Canberra, Australia
    0 Post(s)
    0 Thread(s)
    You can use the js Date object to get information about different dates and make comparisons. Here is an example function that would return the difference in days/months for you using the date object:

    // Compare older vs newer dates
    function dateDiff(older,newer) {
        var data= {};
        // Elapsed milliseconds
        data.elapsed = newer.getTime() - older.getTime();
        // Elapsed Days
        data.days = Math.round((((data.elapsed/1000)/60)/60)/24);
        // Elapsed Months
        var monthDiff = (newer.getMonth()+1) - (older.getMonth()+1);
        var yearDiff = newer.getFullYear() - older.getFullYear();
        data.months = monthDiff + (yearDiff*12);
        // Return data
        return data;
    // Compare the date 1st Feb 2010 with Now and alert the number of days and months elapsed
    var diff = dateDiff(new Date("1 Feb 2010"),new Date());
    alert("Days: " + diff.days);
    alert("Months: " + diff.months);
    You can even compare dates objects directly without using the date object functions, I think using the functions is a little more readable. More info about the js date object:


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts