Paul McFedries' Web Home

JavaScript Programs

Calculating the Number of Days Between Any Two Dates

A common date calculation involves figuring out the number of days between any two dates. For example, you might need to know the number of days between now and the end of the year:

The JavaScript Code

The following JavaScript function accomplishes this:

function days_between(date1, date2) {

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms)
    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY)


This function accepts two Date object arguments—date1 and date2. Note that is doesn't matter which date is earlier or later because this function calculates the absolute value of the difference between them. The constant ONE_DAY stores the number of milliseconds in a day, and then the two dates are converted into milliseconds using the getTime() method. The results are stored in the variables date1_ms and date2_ms.

Next the following statement calculates the absolute value, in milliseconds, of the difference between the two dates:

var difference_ms = Math.abs(date1_ms - date2_ms)
This difference is then converted into days by dividing it by the ONE_DAYS constant. (Math.round() ensures an integer result.)

Here's the JavaScript code that uses this function to calculate the number of days left until the end of the year:


// Store the current date and time
var current_date = new Date()

// Store the date of the next New Year's Day
var new_years_date = new Date()
new_years_date.setYear(new_years_date.getFullYear() + 1)

// Call the days_between function
var days_left = days_between(current_date, new_years_date)

// Write the result to the page
if (days_left > 1) {
    document.write("<b>There are " + days_left + " days left this year.</b>")
else {
    document.write("<b>There is " + days_left + " day left this year.</b>")


Copyright © 1995 - 2014 Paul McFedries and Logophilia Limited