JavaScript Date Objects

This tutorial is part of a web programming course for people who have no programming experience.

We have discussed how object-oriented programming is used to simulate real world objects in our programs. Sometimes we create objects in our programs that represent 'virtual' objects. A date is not something that you can touch, or hold in your hand, but we often use objects in our programs to represent dates. Working with dates and times is so common in programming that many languages have some sort of built-in object for doing so. In JavaScript you can create a date object by invoking the Date() constructor function, which is built into the language (luckily we don't have to define it ourselves). You will soon find out that date objects in JavaScript have lots of methods that you can invoke to help you work with dates and times in your programs. As a teacher, I'm a huge fan of introducing with the Date constructor function as soon as possible because it offers so many interesting, real world problems for my students to wrestle with.

How Computers Keep Track of Dates and Times

Before we dig into the specifics of the Date constructor function, we need to spend a moment understanding how computers keep track of dates and times. Computers keep track of time by counting the number of milliseconds that have elapsed since a given moment in time. Humans keep track of years by counting the number of years that have passed since 0 B.C.. This date, 0 B.C. is known as an epoch because it marks the occurence of an event. In computers, the epoch is January 1, 1970 (at midnight), and all computers start recognize this time as 0 and begin counting from there. This is known as the Unix Epoch (Unix is one of the first operating systems, and it was invented in 1969). Humans read dates as the number of years, months, and days that have elapsed since 0 B.C., while computers refer to dates and times as the number of milliseconds that have elapsed since the Unix Epoch. This number in milliseconds, is often called Unix time, or a Unix timestamp. I just now checked my computer for it's Unix timestamp and it gave me this: 1594675436565. This was the number of milliseconds that had elapsed since the Unix Epoch when I did my check. If I were to check it again a moment later, it would be a bigger number because more milliseconds would have elapsed.

You might be wondering how the computer stores dates before the Unix Epoch. Well, those are simply negative numbers, starting at zeroe and counting backwards.

Here's a fun little diagram to help with visualizing Unix Time. It starts on Jan 1, 1970, which is 0 milliseconds. I have placed another marker roughly where the turn of the century occured. I really don't know how to say that number, let's just say it's about 9 bazillion milliseconds that elapsed between the epoch and the turn of the century. The arrow at the end represents the current time, which when I wrote this article was about 15 bazillion milliseconds.

unix timestamps

If you wanted to calculate how much time elapsed between the turn of the century and the time when I wrote this article you can visualize the problem like this:

unix time line example

To solve the problem you could just subtract the 9 bazillion from the 15 bazillion. Of course you should strive to be more precise that rounding everything to the nearest bazillion, but you that's easy if you make the computer figure everything out to the nearest millisecond. Then you could take the result and convert it from milliseconds into years, days, months, and so on.

If you watched the video that accompanies this lesson, you saw a neat little trick for figuring how long it takes your web page to load in the browser. All I did was add a bit of JavaScript code at the top of the page that checks the Unix timestamp, and assign it to a variable. Then I added another check at the bottom of the page. Then I subtracted the second number from the first and that told me how much time elapsed from when the page first started loading, to when it completed loading. In some ways, it's much easier to do date calculations in milliseconds because we can just compare the difference between two numbers. While it's difficult for us humans to comprehend such large numbers, computers are quite good at it.

Keep all of this in mind as we begin to learn about the Date constructor function and working with date objects in JavaScript.

The Date Constructor Function

To capture the current time you can invoke the Date constructor function without passing in any parameters, like so:

var currentTime = new Date();

The Date constructor returns a date object, which in this case is stored in the currentTime variable. Note that currentTime will store the time when this line of code is executed in the browser. If you re-run this code by repeatedly pressing the F5 key to refresh the page, you'll see the the number of seconds will grow. You'll also notice that logging the variable that stores a date object will produce a string that represents the date in human readable form rather than in milliseconds.

You can pass in parameters when you invoke the Date constructor to create a date object that represents any date/time you like. The first parameter indicates the year, the second indicates the month, and the third represents the day of the month. In this example, the date object created by calling the constructor stores Jan 1, 2000:

var y2k = new Date(2000, 0, 1);

You may have noticed something funny about the second parameter, which is 0. In most programming languages, month numbers start at 0 rather than 1. This may trip you up when you first start working with date objects, but you'll get used to it with some practice.

You could pass even more parameters if you wanted to set the date object to a specific time. A fourth parameter would represent the hour, a fifth would represent the minute, and so on.

Methods of a Date Object

Now that you know the very basics of creating Date objects, we'll turn our attention to the many various methods that you can invoke. It's extremely important for programmers to understand the methods an object has to offer. Methods are the tools you use to solve problems, and you must understand the tools in order to solve problems. I won't cover all the methods that come bundled into a date object, but you can check out this reference for a complete listing:
JavaScript Date Object Reference
There are many other references on the internet as well.

If you want to store the Unix timestamp of a date object in a variable, you can invoke the getTime method like this (note that I'm using the y2k variable that was initialized above:

var timestamp = y2k.getTime();

I used this method in the video to calculate the time it took for the page to load.

You can pull parts of a date out of a date object by invoking various methods whose names start with 'get':

var currentMonth = currentTime.getMonth();
var currentDayOfMonth = currentTime.getDate();
var currentYear = currentTime.getFullYear();

console.log(currentMonth, currentDayOfMonth, currentYear);

Be careful with the getMonth method and remember that a computer counts months starting from 0.

You can alter the timestamp stored within a date object by invoking various methods whose names begin with 'set':

var myDate = new Date();

Again, be careful when using setMonth and remember that the month numbers start a 0 rather than 1.

Another handy method is getDay (not to be confused with getDate). The getDay method returns a number that represents the day of the week for a date. A 0 represents a Sunday, a 1 represents Monday, and so on (notice that the computer starts counting from 0 here again). This code sample reveals that y2k occured on a Saturday:


Yet another handy method of a date object is toDateString, which returns a string that represents a date in human readable form:


There are many other methods that you can invoke on a date object which I will not cover in this lesson. But it's very well worth your time to look at the reference I mentioned above (or find another one if you prefer). Knowing about the methods that are available are critically important to understanding the capabilities of an object. I cannot stress this enough. And when building a real world application, it's likely that most of the constructor functions you use are designed by other programmers. So it's very important that you read and understand references like the one I mentioned earlier. It's also very important to spend time tinkering with various methods of an object, because they can have some quirks (as we have when working with month numbers). If you do the worksheet that accompanies this lesson, you'll discover a few other quirks when working with date objects.

NEXT LESSON: JavaScript and the DOM