Using Objects and Methods

Imagine that your web page would like to be aware of the current data. You could be prompting the user for time-related values such as month, hour and minute but it would be better to dynamically compute the date and determine, say, whether it is spring or lunchtime and so forth. We'll now see how to do that using the computer's clock instead of prompt(). Note that this is not the processor (CPU) clock that keeps a tempo for the hardware, but the conventional time, day and date clock.

Displaying the Date Dynamically

We can display the current date and time on a web page, using some built-in JavaScript to access the computer clock, and the string concatenation operators we already know. For example, the following box displays the current date and time, as reported by your computer:

You loaded this page on at

By the way, the HTML code for that box above is as follows:

<div id="date_today">
  <p>You loaded this page on <span id="date1"></span>
    at <span id="time1"></span></p>

Notice that we have two spans with CSS id's. This will make it easy for us to create JS code that will insert date and time values in these two spans using their id's. For example, executing the following JS code would assign a value to the first span box equal to January 1st of the year Wellesley College was founded!

document.getElementById("id").innerHTML = "01/01/1870"

If you reload this page, you'll notice that the date and time change to the current time of your reload. (You may see a slight flaw in the appearance (missing a leading zero in the minutes or seconds); we'll fix that later.)

Before we explain the JavaScript code that can do this, we need to understand how time is represented in JavaScript. We begin by creating a Date object:

var dateObj2 = new Date();  // The name tries to convey that this is a date object

Similarly to what we've seen before, the keyword var in var dateObj2 creates a new variable box named dateObj2 for storing a value. What we haven't seen before is the keyword new, which causes a JavaScript object to be created. In this case, the object represents the current date and time. JavaScript comes equipped with lots of pre-defined object types like Date. For those who have the time and interest, there is optional reading for a general description of objects. For now, you can think of an object as a collection of information, not just a single value.

Example Date Methods

We can extract information from a Date object by invoking methods on it. The table below shows some of the important methods that Date objects understand. The elements of the Value column are dynamically computed by evaluating the JavaScript expressions in the Expression column, so reloading the page will update these appropriately.
Expression Value Notes
dateObj2.getFullYear() Full year
dateObj2.getYear() Avoid this! Varies from browser to browser
dateObj2.getMonth() 0=Jan, 1=Feb, ..., 11=Dec
dateObj2.getDate() 1 to 31
dateObj2.getDay() 0=Sun, 1=Mon, ..., 6=Sat
dateObj2.getHours() 0 to 23
dateObj2.getMinutes() 0 to 59
dateObj2.getSeconds() 0 to 59
dateObj2.getTime() Milliseconds since Jan 1, 1970 (the "epoch")

You'll note that all of these methods "return" numbers, extracting one piece of information out of the collection that the object comprises. Usually, they are pretty intuitive:

Later, when we talk about arrays, we'll try to justify why certain things are numbered starting at zero. But for now, we'll just understand that these are what we have to work with.

W3 Schools has a complete list of methods for Date objects.

Object Notation

Let's discuss the notation for objects. First, imagine that we create two Date objects, a few seconds apart:

var obj1 = new Date();
alert("obj1: "+obj1);
var obj2 = new Date();
alert("obj2: "+obj2);
var sec1 = obj1.getSeconds();
var sec2 = obj2.getSeconds();
alert("seconds in obj1: "+sec1+" and in obj2: "+sec2);
var diff = sec2 - sec1;
alert("difference is "+diff);

You can think of each new Date() expression as taking a snapshot of the computer clock, recording those values at that moment in time.

Our mental picture of this example might be like this:

two date objects
Two date objects and info extracted from them

Because objects contain a collection of information, possibly quite large, we picture it as a round thing. (Here, each object is a light blue circle.) We can store these things in variables (labeled boxes), just like we store anything in variables, including numbers, strings, and booleans. The other variables just contain numbers; we're used to those.

Given an object in a variable, we use a method to do something with it (such as extracting some data) using the following syntax:


The dot is important: it separates the object (or a variable containing an object) from the method that is being used. Some methods need additional arguments; we haven't seen any yet, but we will later in the course. For now, we'll just see an empty pair of parentheses, but these are required.

The examples we saw above fit that pattern:

var sec1 = obj1.getSeconds();  // get seconds out of obj1
var sec2 = obj2.getSeconds();  // same, but for obj2

Date Formatting

Now let's return to our date and time display. A date object contains a collection of information about the date and time, but for human-readability, we will need to format that data in some conventional way, using, for example, slashes and commas to separate the various numbers.

Here is the date, formatted as is done in the United States and a small handful of other countries. This box has text in Spanish, unlike our earlier box:

Ha cargado esta página en a las .

The HTML for that box above is just this:

<div id="date_today2">
  <p>Ha cargado esta página en <span id="date2"></span>
    a las <span id="time2"></span></p>

Here is some JavaScript code that inserts the formatted date and time into the box above. (Note the two empty span elements with IDs that we'll use below.)

// create a date object, representing this moment, and store it
var dateObj = new Date();

// format info about the day
var the_date = dateObj.getDate();
var the_month = dateObj.getMonth() + 1; // Add 1 because Jan is 0, etc.
var the_year = dateObj.getFullYear();
var current_date = the_month + "/" + the_date + "/" + the_year;

// format info about the time
var the_hour = dateObj.getHours();
var the_minute = dateObj.getMinutes();
var the_second = dateObj.getSeconds();
var current_time = the_hour + ":" + the_minute + ":" + the_second;

// insert the formatted strings into the document.
document.getElementById("date2").innerHTML = current_date;
document.getElementById("time2").innerHTML = current_time;

(You can also view the page created by embedding this code in a complete HTML file for displaying the date.)

Let's examine the code. It is a sequence of JavaScript statements, which will be executed sequentially by the browser. The first statement (line 2) creates a Date object representing the current date and time, and stores it in a variable named dateObj. The next block of statements (lines 4-8) extract components of this Date object and piece them together to construct a description of the date, like 10/13/2015. The next block of statements (lines 10-14) similarly extract components of this Date object and piece them together to construct a description of the time, like 17:22:44.

The final document.getElementById("id").innerHTML statements each inserts a string into the span with the given ID, thereby displaying the date and time on the page. The surrounding text is fixed. You've seen this sort of trick in lab; we'll do more with this later in the course. Here's another copy of the HTML code they inserted it into:

  <p>Ha cargado esta página en <span id="date2"></span>
    a las <span id="time2"></span></p>

Practice the behavior of the code by using the execution box below. Change the code to display the date in the format that most of the world uses, namely, DD/MM/YYYY.


Exercise on Date Formatting

Objects in General (OPTIONAL READING)

Dates are one kind of object. In JavaScript, an object is a kind of value that has two important characteristics:

Both properties and methods are selected from an object using dot notation. In the examples above, we only used methods. You can tell we're using a method rather than selecting a property by the presence of parentheses after the name.

Other Methods

We've used the example of dates to teach you about:

Lots of other objects and methods exist in JavaScript.

Here's another method, this time on numbers, the toFixed() method:

The toFixed() method returns a string representation of the number, with the number of decimal places given by the argument. It does not change the value of the variable, as the last step shows.

The toFixed() method operates on numbers. A method that operates on strings instead is the .indexOf() method. See if you can guess what it does:

Yes, the indexOf() method searches for one string inside the main string object.

Wait, are numbers and strings objects? Earlier in this reading, we suggested that objects (pictured with light blue circles) were collections of information, unlike simple values like numbers and strings. It turns out that objects and methods are such a useful way of organizing information that many programming languages treat everything as a kind of object. JavaScript allows numbers and strings to be treated as objects when it's convenient, as it is here.

Later in the course, we'll see how parts of the HTML document can be represented and manipulated using objects. This is the Document Object Model, or DOM.

Names for Months and Days

The earlier date manipulation code was all numerical. That's partly because JavaScript is used around the world, and they decided not to have a built-in function to map month zero to January when it could just as easily have been Janvier (French), Enero (Spanish) or Styczen (Polish).

Despite this, we decided to implement a simple function that maps month-numbers (ranging from 0 to 11) to English month-names. The function is named monthName(). We also wrote one to map day-numbers (ranging from 0 to 6) to English day-names. Try them out:

We'll show you how it's implemented a bit later, but for now, please take it on faith.


How would you print the name of the month 10 months from now?

Date Objects for Other Dates

All along, we've created Date objects as a snapshot of the current computer clock, but we don't have to. We can create a Date object for any date of our choosing, just by giving a string to the Date() function. Here's a bit of code that will tell us what day of the week Christmas falls on in 2015:

Note, though, that if you mess up the syntax of the string describing the date and time, you'll get an invalid Date object and nothing good will happen:

You can fix the above by removing the "am" part; remember that "13:15" would be "1:15pm", so the "am/pm" part is unnecessary.


Solutions to Exercises