Displaying The Days Between Two Dates Via JavaScript / DOM
Recently asked on Yahoo! Answers:
I am not a programmer, but i need the codes and add it to an existing webpage format. What i need exactly is to show in the page a kind of table identifying a date in the future, the current date, and the number of days (the difference between the two dates) from the current date to the mentioned future day. Its like a countdown on how many days are left before that future date comes…
This is very easy to accomplish via JavaScript; because JavaScript treats time as an integer, it’s all just math, plus changing the values of a couple of DIVs via JavaScript’s DOM manipulation abilities. So let’s get right to it.
Step 1: The HTML Table
We’ll make simple table to display the results. That table will have three DIVs associated with it: One that we will use to display the current date; one which will contain our future date; and one that will display the number of days between the two.
The current date and days between dates DIVs we will leave blank. But inside the future date DIV, we’ll provide the date in some commonly understood date format. For this exercise, because of the way the question is wording, I’m using the standard U.S. “month, day fullyear” long-date format.
| Today's Date | 70th Anniversary Of D-Day | Days Remaining Until Anniversary |
|---|---|---|
|
June 6, 2014
|
Step 2: Add The OnLoad Event To The Body Tag
Since we’re working with the HTML right now, let’s go ahead and add the onload event to the body tag that will trigger our JavaScript function to figure out today’s date. Our function will be called getDaysBetweenDates(), so that’s what the onload event will call.
Step 3: Some Helper JavaScript Functions
Before we get on to the getDaysBetweenDates() function, we need two helper functions: one that will return the name of a month from an integer argument we’ll give it, and the other that will format numbers over 999 with commas. They will be called monthName and formatThousands, respectively.
The monthName function is self-explanatory. JavaScript’s getMonth() function will give us an integer from 0 (January) to 11 (December) for any date; we want this function to give us the actual name of the month.
function monthName(input) {
var out;
input++;
switch(input) {
case 1:
out = 'January';
break;
case 2:
out = 'February';
break;
case 3:
out = 'March';
break;
case 4:
out = 'April';
break;
case 5:
out = 'May';
break;
case 6:
out = 'June';
break;
case 7:
out = 'July';
break;
case 8:
out = 'August';
break;
case 9:
out = 'September';
break;
case 10:
out = 'October';
break;
case 11:
out = 'November';
break;
case 12:
out = 'December';
break;
default:
out = 'No Month';
}
return out;
}
The formatThousands() function is a bit more involved.
It first converts the inputted number to a string by adding an empty character to the input. It then runs the number through a regular expression, breaking it into chunks of three numbers each.
For each grouping of three numbers with at least one number before them, we break the number into the three numbers and whatever preceeds them, and insert a comma in the middle.
function formatThousands(input) {
var theNum = input;
theNum += '';
var reComma = /(d+)(d{3})/;
while (reComma.test(theNum)) {
theNum = theNum.replace(reComma, '$1' + ',' + '$2');
}
return theNum;
}
Step 4: The getDaysBetweenDates() Function
On to the function at question. We begin by assigning to some JavaScript variables the three DIVs in our table: Today’s date, the future date and the number of days between the dates.
Next, we get the current date, plus the date contained in the future date DIV, then assign those to variables.
As I’ve previously mentioned, JavaScript records time as the number of milliseconds that have passed since midnight, January 1, 1970. That means figuring out the difference between two dates is as simple as subtracting the earlier date from the later date.
But that’s going to give us a gigantic integer representing milliseconds. We want days. Again, math to the rescue.
Since there are 24 hours in a day, 60 minutes in an hour and 60 seconds in a minute, we can compute the number of milliseconds in a day via multiplication: 86,400,000 (that’s 86.4 million). So, we set that to a variable.
Then, we divide the number of milliseconds we get by subtracting today’s date from the future date by the number of milliseconds in a day. That leaves us with a weird fraction, so we then use Math.ceil() to round the result up to the next day (since any fraction of a day is, technically, another day).
We now have the number of days between the two dates. (A day isn’t actually 24 hours long, but so long as we don’t use dates that are spectacularly wide apart, the result should be correct). So, all we have left is to add the dynamic stuff — today’s date and the number of days between dates — to their respective DIVs in the table.
Note that we use the monthName() and formatThousands() helper functions from Step 3 in these final steps.
function getDaysBetweenDates() {
//get the DIVs where we will display the results
var todayDiv = document.getElementById('todayDiv');
var futureDiv = document.getElementById('futureDiv');
var resultDiv = document.getElementById('resultDiv');
//today's date
var rightNow = new Date();
//get future date from the furure date DIV
var futureDate = new Date(futureDiv.innerHTML);
//how many milliseconds are there in one day?
var msInOneDay = 86400000;
//subtract today's date from future date
var dateDiff = futureDate - rightNow;
//divide by microseconds in one day for # of days
//round down so we don't show a weird fraction
var daysDiff = Math.ceil(dateDiff / msInOneDay);
//set the value of the DIVs to be the results
todayDiv.innerHTML = monthName(rightNow.getMonth()) + ' ' + rightNow.getDate() + ', ' + rightNow.getFullYear();
resultDiv.innerHTML = formatThousands(daysDiff);
}
And that’s all there is to it. You can see this in action here:
http://www.dougv.com/demo/js_datediff_days/
To use it yourself, just copy and paste the appropriate sections (JavaScript, BODY onload, and table / DIVs) to your page. I distribute all software under the GNU GPL version 3.
Related Posts
- Displaying The Correct Time For World Cities With AJAX / JavaScript / DOM (30.3)
- Displaying An Image On A Web Page Based Upon The Current Time With JavaScript / DOM (28.4)
- Displaying And Hiding Content Via JavaScript / DOM And The OnClick Event (26.2)
- Displaying A New Image Based On Image Choices Via Checkboxes, the HTML DOM and JavaScript (25.7)
- Displaying A Random Yahoo! Search Every 30 Seconds With JavaScript And PHP (19.5)
The numbers inside parentheses are relevance scores. Scoring is based, in order of priority, on title, category, content and tags. The higher the score, the more likely that post relates to this post.


Comments Closed