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
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
prompt(). Note that this is not the processor (CPU)
clock that keeps a tempo for the hardware, but the conventional
day and date clock.
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> </div>
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.)
We begin by creating a
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 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
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.
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
Expression column, so reloading the page will update
|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:
.getMinutes()returns a number from 0 - 59
.getFullYear()returns a number like 2015
.getHours()returns a number from 0 - 23, which is intuitive for everyone in the world except for Americans.
.getDate()returns a number from 1 - 31, depending on the month.
.getMonth()returns a number from 0 - 11, depending on the month. This is deeply unintuitive for anyone except computer scientists, who are accustomed to things being numbered starting at zero. And they still get tripped up by things like
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
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
snapshot of the computer clock, recording those values at that
moment in time.
Our mental picture of this example might be like this:
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
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> </div>
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.)
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
next block of statements (lines 4-8) extract components of
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
object and piece them together to construct a description of the time,
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
<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.
<script>tags. They are implied.
.html()code with an
alert(), so that the code is obvious when it's running.
colorand much more. Date objects wouldn't have that.
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.
We've used the example of dates to teach you about:
Here's another method, this time on numbers,
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?
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
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.
Dateobject is used to manipulate dates and time. The expression
new Date()creates a
Dateobject representing the current date and time. Methods like
getHours()are used to extract components from a