Date
Object Operations with date/time valuesWe can display the current date and time on a web page. For example:
If you reload this page, you'll notice that the date and time change appropriately.
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 now = new Date();
As we've seen before, the keyword var
in var now
creates a new
variable box named now
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
. Other examples are
Number
, Array
, or Image
.
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 |
---|---|---|
now.getFullYear() | Full year | |
now.getMonth() | 0=Jan, 1=Feb, ..., 11=Dec | |
now.getDate() | 1 to 31 | |
now.getDay() | 0=Sun, 1=Mon, ..., 6=Sat | |
now.getHours() | 0 to 23 | |
now.getMinutes() | 0 to 59 | |
now.getSeconds() | 0 to 59 | |
now.getTime() | Milliseconds since Jan 1, 1970 (the "epoch") | |
now.getYear() | Deprecated. Use .getFullYear() instead. |
W3 Schools has a complete list of
methods for Date
objects.
A date object contains a collection of information about the date and time. The default way that Javascript formats this object is shown below:
For better human-readability, we will need to format it 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:
Here is JavaScript code that does this: :
// create a Date object, representing this moment, and store it var today = new Date(); // format info about the day var the_day = today.getDate(); var the_month = today.getMonth() + 1; // Add 1 because Jan is 0, Feb is 1, etc. var the_year = today.getFullYear(); var current_date = the_month + "/" + the_day + "/" + the_year; // format info about the time var the_hour = today.getHours(); var the_minute = today.getMinutes(); var the_second = today.getSeconds(); var current_time = the_hour + ":" + the_minute + ":" + the_second; document.write("<blockquote>In Wellesley, MA, the date is " + current_date + " and the time is " + current_time + ".<\/blockquote>");
Let's examine the code. It is a sequence of JavaScript statements,
which will be executed sequentially by the browser. The first statement
creates a Date
object representing the current date and time,
and stores it in a variable named today
. Subsequent
statements extract components of this Date
object and piece
them together. The final document.write()
statement displays
the date and time on the page.
As shown below, we could get by with only the single
variable today
. Although the other variables are not strictly
necessary, they can help to make the code more readable. Note that
there's nothing special about naming the variable today
. We
could have called it anything else.
// create a Date object, representing this moment, and store it var today = new Date(); document.write("<blockquote>In Wellesley, MA, the date is " + (today.getMonth() + 1) + "/" + today.getDate() + "/" + today.getFullYear() + " and the time is " + today.getHours() + ":" + today.getMinutes() + ":" + today.getSeconds() + ".<\/blockquote>");
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.
Remember:
<script>
tags. They are implied.
alert()
rather
than document.write()
. In
fact, document.write()
will not work properly in an
execution box.
Date
objectsThe above formatting example is important to understand the
different get...()
methods to access different properties
of the Date
object. However, once you have a good familiarity
with these methods, it is tedious to have to format a date with so many
lines of code. The table below contains a list of some formatting methods
that we will be using in our examples.
Expression | Value |
---|---|
now.toDateString() | |
now.toGMTString() | |
now.toLocaleDateString() | |
now.toLocaleString() | |
now.toLocaleTimeString() | |
now.toTimeString() | |
now.toString() |
We saw how to create a date object with new Date()
. This expression,
always evaluates to the current date/time. However, one can use the same method to create other
dates. The method Date()
is known in a programming language as the constructor,
a special method that allows us to create new objects. To achieve this, the constructor,
can be invoked with arguments, which are values provided inside the parantheses.
We have seen many examples of functions
or methods that take arguments (alert
, prompt
,
document.querySelector
, etc.) In all these cases, the kind of value that we passed
as an argument was always a string.
However, a constructor
method is special and it can be invoked with different
kinds of values and different number of arguments. Below are shown the different ways
one can invoke Date()
:
var date1 = new Date(); var date2 = new Date(milliseconds); var date3 = new Date(dateString); var date4 = new Date(year, month, day); var date5 = new Date(year, month, day, hours, minutes); var date6 = new Date(year, month, day, hours, minutes, seconds, milliseconds);
Being able to create objects that are different from the current day, allows us to perform operations with dates such as comparing them, adding, and subtracting.
Suppose you want to create a date counter to let one know how many days until a certain day such as Christmas, Thanksgiving, or start of Spring Break.
To do that, you first create a date object with the desired date, then check to see if that day has not already passed, and if that is the case, calculate the number of days left.
There is only one problem, when subtracting two days, the result is always milliseconds. One will need to write some code to convert milliseconds in days or other desired unit times (months, etc.).
The code below shows the number of days left until the start of Thanksgiving.
What happens if you change the date from "2015/03/19" to "2014/03/19"? Why?
Replace the argument "2015/03/19" with the proper number and values of arguments
to use in the constructor invocation: Date(year, month, day)
.