Javascript Dates-The Complete Reference
Of all the core Javascript objects, I find Dates to be the most fascinating. Once you learn a few small tricks everything about Javascript Dates just seem to fall into place and you find that there’s really nothing at all that you can’t do with them, quickly, and easily.
This reference will cover the Javascript Date Object, how it stores Dates, how you can manipulate them, create calendars, countdown timers, prototype them to add your own functionality, as well as provide a complete method reference.
Julian Dates
Julian Dates are a method of referencing time and dates based on how much time has passed since an arbitrary number in the past. For instance,
149 days have presently passed this year. If we know that January 1 begins on a
Monday , then we know that day 2 represents a
Tuesday in January. If we know there are 31 days in January then we know that day 32 represents the first of February and we can figure out that February 1st fell on a
Thursday.
Javascript (and most languages) handle dates exactly as described above, only in much grander fashion. The epoch or starting point of Javascript’s date system isn’t January 1 of this year, but rather January 1, 1970 Greenwich Mean Time, and it doesn’t count just days! No Javascript counts the number of milliseconds that have passed since January 1, 1970 and presently that number is 1,180,503,305,390.
var milliId=document.getElementById(‘milli’);
var milli;
function showmilliseconds() {
milli = new Date();
milliId.innerHTML=formatNumber(milli.getTime());
setTimeout(“showmilliseconds()”, 297);
}
showmilliseconds();
Midnight, January 1, 1970 GMT is represented as zero by Javascript. Positive numbers indicate dates after 1970 and negative numbers indicate dates prior to 1970. For instance -1000 represents 11:59:59pm, December 31, 1969. Remember Javascript counts in milliseconds and there are 1000 milliseconds in a single second so -1000 represents 1 second.
By a great coincidence Unix also uses January 1, 1970 as it’s epoch date which means a timestamp in Javascript will match a timestamp on your server as long as you take some care with the timezones!
It will be quite a while before humanity has to worry about running out of dates! Javascript can readily handle around 285,616 years on either side of the 1970 epoch.
Creating A New Date (Parsed)
To create a new Date all you have to do is to ask for one!
var myFirstDate = new Date();
This will create a new date object and since we did not specify a specific date or time, the date will be equal to the instant it was created.
The Javascript Date Object has a very powerful date parser. While there are several ways to create and set Dates. The one you’re most likely to use is simply to specify the date itself, as a string, when creating a new date.
var myDate = new Date(‘January 16, 1988’);
Since we didn’t specify a time the Date which is created will be for midnight in the browser’s timezone on January 16, 1988.
var myDate = new Date(‘January 16, 1988 2:54:16 pm’);
Here we specify a specific time (note that there’s a space between the time and pm). Since we didn’t specify a timezone the browser will use the user’s timezone. We could also have used millitary time (14:54:16).
Here we’ll actually specify a time zone GMT in this case and below we’ll print it out.
var myDate = new Date(‘January 16, 1988 2:54:16 pm GMT’);
Sat Jan 16 22:54:16 UTC+0800 1988
Unless you actually live in the Greenwich Mean Timezone, the date requested and the date printed are unlikely to match. The created date is actually 2:54:16 in the GMT timezone, however when we printed the date out, since we didn’t specify anything special, the date was printed in the Browser’s time zone so the browser did a little conversion for us to ensure the time we printed was the ACTUAL time relative to the browser.
That’s a little confusing so let’s try for something different. Every New Years Eve, the city of New York holds a big celebration and the ball is dropped at precisely midnight in the eastern timezone. So lets create a date for that event.
var myDate = new Date(‘January 1, 2000 EST’);
Since we didn’t specify a time, Javascript will assume midnight for us, we did specify a time zone so the actual time will be midnight in the eastern time zone.
Now when we print the date out we’ll get that little timezone conversion and you can see what time the ball will be dropping in your timezone! (of course people in the eastern timezone will see the “correct”
time).
Sat Jan 1 13:00:00 UTC+0800 2000
Creating A New Date (arguments)
You can also create a new date by passing the date values as arugments to the Date object. The arguments are Year, Month, Date and optionally hours, minutes, seconds, and milliseconds. The first argument, year, is special. If it’s a string the Date object will try to parse it (see previous section), if it’s a long integer it will try to use it as a julian number. If there are more than one argument it will build the date from your supplied arguments.
var d1 = new Date(‘January 1, 1970’); // Date as a parse
var d2 = new Date(0); // Date as a julian number
var d3 = new Date(1970, 0, 1); // Date as arguments
Notice we use zero as the month when creating d3, that’s because Javascript months go from 0 to 11 where January is zero. This is a pretty big gotcha if you’re not careful!
The argument list is as follows…
dateVar = new Date(year, month, date[, hours[, minutes[, seconds[,ms]]]]);
Working With Julian Day Numbers
Working with Julian Dates requires division and modulus. Division will discard the portion of the date you no longer need and modulus (which is the remainder of division) will return the portion of the date you are looking for.
Most people don’t need milliseconds when doing date calculation, so we just divide the Julian Date Number by 1,000. So if we have a Julian Day Number of 1,177,303,066,354 then dividing this by 1,000 will give us a day number of 1,177,303,066 — a number which no longer holds information about the milliseconds in the date.
To get the number of seconds this represents, we take the modulus of 60 because there are 60 seconds in a minute.
var dayNumber = 1177303066;
var seconds = dayNumber % 60; // seconds=46
Now that we have the number of seconds we discard the seconds from the Julian date by dividing it by 60.
var dayNumber = 1177303066;
var seconds = dayNumber % 60; // seconds=46
dayNumber = dayNumber/60; // dayNumber = 19,621,717
So now our day number has been stripped of milliseconds and seconds. We can find out how many minutes the number represents by taking the modulus of 60 since there are 60 minutes in an hour.
var dayNumber = 1177303066;
var seconds = dayNumber % 60; // seconds=46
dayNumber = dayNumber/60; // dayNumber = 19,621,717
var minutes = dayNumber % 60; // minutes=37
And we can discard the minutes from the original number by dividing it by 60. What remains are hours and days. We can get the hours by taking the modulus of 24 since there are 24 hours in a day. Then divide the daynumber by 24 to discard the hours, leaving only the number of days.
var dayNumber = 1177303066;
var seconds = dayNumber % 60; // seconds=46
dayNumber = dayNumber/60; // dayNumber = 19,621,717
var minutes = dayNumber % 60; // minutes=37
dayNumber = dayNumber/60; // dayNumber = 327,028
var hours = dayNumber % 24; // hours = 4
dayNumber = dayNumber/24 // dayNumber = 13,626
Or 13,624 days between January 1, 1970 and
Mon Apr 23 12:37:46 UTC+0800 2007
Countdown Timers In Javascript
In the previous section we broke a day number out into its component milliseconds, seconds, minutes, hours, and days. The number we used was the number of milliseconds that had elapsed since January 1, 1970. But we could just as easily have used another date. Lets take the difference between now and the end of the year.
var now = new Date();
var newYear = new Date(‘January 1, ‘+(now.getFullYear()+1));
var diff=newYear–now;
This code creates two julian dates, “now”
and “newYear”
. By subtracting “now”
from “newYear”
we get an integer which represents the difference between the two dates, specifically:
18,613,597,250.
We can use division and modulus to extract the time from this number just like we did in the previous section only now we’re computing the difference between now and the new year instead of a date and January 1, 1970.
This article is generating “now”
and “newYear”
in real-time so the values below are the actual values until the new year!
var now = new Date();
var newYear = new Date(‘January 1, ‘+(now.getFullYear()+1));
var diff=newYear–now;
var milliseconds=Math.floor(diff % 1000);
diff=diff/1000;
var seconds=Math.floor(diff % 60);
diff=diff/60;
var minutes=Math.floor(diff % 60);
diff=diff/60;
var hours=Math.floor(diff % 24);
diff=diff/24;
var days=Math.floor(diff);
This gives us a value of
215 Days, 10 hours, 26 minutes, 37 seconds, until Tue Jan 1 00:00:00 UTC+0800 2008.
Making a Timer
In the example above now is equal to the instant it is created while newYear is a constant value, always equal to January 1 of next year. So it’s actually very easy to make a timer. All we have to do is turn the code above into a function, set up a setTimeout command, and create a html division somewhere on the page to hold our timer. Here’s the new code!
<!– This span is where the countdown timer will appear –>
<div id=‘countdown’></div>
<script type=“text/javascript”>
// Here’s our countdown function.
function happyNewYear() {
var now = new Date();
var newYear = new Date(‘January 1, ‘+(now.getFullYear()+1));
var diff=newYear–now;
var milliseconds=Math.floor(diff % 1000);
diff=diff/1000;
var seconds=Math.floor(diff % 60);
diff=diff/60;
var minutes=Math.floor(diff % 60);
diff=diff/60;
var hours=Math.floor(diff % 24);
diff=diff/24;
var days=Math.floor(diff);
// We’ll build a display string instead of doing document.writeln
var outStr = days + ‘ days, ‘ + hours+ ‘ hours, ‘ + minutes;
outStr+= ‘ minutes, ‘ + seconds + ‘ seconds until the new year!’;
// Insert our display string into the countdown span.
document.getElementById(‘countdown’).innerHTML=outStr;
// call this function again in exactly 1 second.
setTimeout(“happyNewYear()”,1000);
}
// call the countdown function (will start the timer)
happyNewYear();
</script>
When the function is called (every second), now is always set to the current, ever advancing date, while the newYear always remains a constant. So the function works to countdown the passing time to the destination date (new year).
And here’s the result! 215 days, 10 hours, 24 minutes, 55 seconds until the new year!
Does the time appear a bit off? Maybe because right now you’re in Daylight time and the new year is in daylight savings time! If this is the case, once everyone falls back the timer will again be in sync with your expectations!
Making A Clock
Making a clock is very similar to making a countdown timer. All we have to do is to create a new date and get it’s hours, minutes, and seconds.
<!– This span is where the clock will appear –>
<div id=‘clockDiv’></div>
<script type=“text/javascript”>
function clock() {
var now = new Date();
var outStr = now.getHours()+‘:’+now.getMinutes()+‘:’+now.getSeconds();
document.getElementById(‘clockDiv’).innerHTML=outStr;
setTimeout(‘clock()’,1000);
}
clock();
</script>
And the result (in military time): 13:35:4
Getting The Number Of Days In A Month
Javascript has a little quirk where a date of zero will set the date to be the last day of the previous month. Likewise is there are 30 days in a month and you set a date of 31 it will be the 1st day of the next month, a date of 40 would be the 10th day of the next month. This can lead to some very weird funkiness if you’re not careful but we can definitely exploit this for a useful prototype which will give us the number of days in a specific month. We’ll do this up as a prototype so it’s available to all our Dates.
Date.prototype.daysInMonth = function () {
return new Date(this.getFullYear(), this.getMonth()+1, 0).getDate()
}
var d = new Date();
document.writeln(‘Number of days in this month: ‘+d.daysInMonth());
And the result (live!):
31
Getting The Name Of The Day And Month
While the Javascript Date Object has many useful features, one glaring oversight is that when you ask it for the day or month it will return only the numerical representation. This is easy enough to fix with prototypes however.
Date.prototype.getDayName = function(shortName) {
var Days = [‘Sunday’, ‘Monday’, ‘Tuesday’, ‘Wednesday’, ‘Thursday’, ‘Friday’, ‘Saturday’];
if (shortName) {
return Days[this.getDay()].substr(0,3);
} else {
return Days[this.getDay()];
}
}
Date.prototype.getMonthName = function() {
return [‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’][this.getMonth()];
}
These two methods are pretty simple to use. If you want the month name just do…
var d = new Date();
month = d.getMonthName();
If you want the name of the day, do…
var d = new Date();
day = d.getDayName();
If you’d like the three character day name (mon/tue/wed, etc) then pass an argument to getDayName. As long as the argument isn’t false, null or any other falsey value the name will be shortened to its three letter equivalent.
var d = new Date();
day = d.getDayName(true);
Making a Calendar
Making a calendar is a bit more complex than making a timer or clock but mostly because any calendar script is going to be generating HTML to display the calendar and whenever you have programs writing programs things always get a bit funky! We’ll do this as a prototype so all you have to do is create a date with the month you want the calendar for and use the .calendar() method.
Note this prototype assumes you’ve included the getMonthName() and daysInMonth() prototypes described above, the calendar will break if they are not included in your code.
Date.prototype.getMonthName = function() {
return [‘January’, ‘February’, ‘March’, ‘April’, ‘May’, ‘June’, ‘July’, ‘August’, ‘September’, ‘October’, ‘November’, ‘December’][this.getMonth()];
}
Date.prototype.daysInMonth = function () {
return new Date(this.getFullYear(), this.getMonth()+1, 0).getDate()
}
Date.prototype.calendar = function() {
// The number of days in the month.
var numDays = this.daysInMonth();
// Get the starting day of this calendar, mon, tue, wed, etc.
var startDay= new Date(this.getFullYear(), this.getMonth(), 1).getDay();
// We’ll build our table in the buildStr variable then pass what we build back.
// This will be a HTML table — Build the header rows…
var buildStr =‘<table summary=”Calendar” class=”calendar” style=”text-align: center”>’;
buildStr+=‘<tr><td colspan=7>’+this.getMonthName()+‘ ‘+this.getFullYear()+‘</td></tr>’;
buildStr+=‘<tr><td>Sun</td><td>Mon</td><td>Tue</td>’;
buildStr+=‘<td>Wed</td><td>Thu</td><td>Fri</td>&