Mike: Oh, yes! The last one. There’s no operator between x2 and the literal string
".".
Professor: Precisely. These are two separa te expressions and you cannot put one
expression afte r another without an opera tor in between. I forgot to type + there. But
that’s just perfect bec ause we discovered that the D evTools also oer a hand y too l for
finding syntax errors. When things go wrong, opening the DevTools shall become
second nature.
Note that in real p rograms a syntax error is norm ally much easier to catch than a
logic error. A syntax error c an be either a spelling mistake or an error in g rammar or
context, such as a missing operator or a n un declared variable. The JavaScript Console
will usua lly direct you to the exact location of a sy ntax error. Logic errors, h owever,
are flaws in the conception of the algorith m and there’s no way a tool can tell you
automatically wh at or where an error is. A logic error can also be a consequence
of a semantic error. This type of e rror occur s when you misuse syntax rules in a
way that they are not violated but the semantics or meaning is not wha t you had in
mind. An example of a semantic error was when we mistakenly used a plus sign
as a concatenation instead of an additio n operator in our ar ithmetic mean example.
However, you already know how to use various debugging tools to find logic and
semantic errors.
Let’s return to our lottery numbers. We learned how to produce two dierent random
numbers but in fact we need to find six diere nt numbers. Unfortunately, our last ap-
proach isn’t a very elegan t solu tion to the problem when we are after more than just a
few numbers. For one thing, we would need six dierent variables to hold six diere nt
values. Next, we would have to write 15 dierent comparison expressions because ev-
ery selected number must be dierent from any other selected number. If we wanted
to produce more than six dierent numbers, then things would get significantly worse.
Does all this sound familiar to you?
Maria: We have again stumble d upon exactly the same problem as we did with prim e
numbers, and with the a rithmetic mean calculation.
Professor: Indeed we have. Only this time we actually need to store individual num-
bers. We’re going to learn how to do that the next time.
8.5 Date Object
Professor: Another handy obje ct built into the JavaScript language is Date, which
is used to represent a single moment in time. There is one fundamental dieren ce
between Math and Date objects, though. As you don’t really need more than a single
Math object in a program, it is not hard to imagine the usefulness of having many
Date objects, each holding a dierent moment in time. That’s why the Date object
is not an “ordinar y object. Rather, it represents a class of obje cts and is hence a data
type. You can view Date as a b lueprint for making objec t instances of the Date class.
If you therefore want to use a Date object, you first need to construct an object in-
stance by means of the Date() constructor and the new operator:
158 Meeting 8. Introducing Objects
var thisMoment = new Date();
Notice that the object is declared using the var keyword like any other variable. Th e
Date() function, which has the same name as the class of objects it represents, is
called a constructor because it helps to construct a new object. If you want to cr eate
an object, then you mu st use the constructor toge ther with the n ew operator. It is also
possible to call Date() as an or dinary f unction, without the new o perator, in which
case it only returns a string representing current time and date and you do n’t get an
object.
Maria: Are the rules for naming an object the same as they are for a variable?
Professor: I ndeed they are.
Mike: Yo u said that it is possible to have many dierent m oments in time. How do
you set them?
Professor: You can set a specific moment in time already at the time of the object
creation. There ar e many dierent ways to call the constructor. For example:
//Creates a Date object instance set to the current time and date.
new Date()
//Creates a Date object instance set to milliseconds past midnight
//1/1/1970.
new Date(ms)
//Creates a Date object instance representing a specific moment
//in time.
new Date(year, month, day, hours, minutes, seconds, ms)
The name of the constructor is always the same and the JavaScript inter preter decides
which one to use de pending upon the number and types of the passed arguments. If
no argu ments are provided, then the current tim e and da te are used.
The second form when one n umeric argument is passed is in te resting. It is taken as
the number of milliseconds past (or befor e, if it is negative) midnight on January 1,
1970 u sin g Coordinated Universal Time. This is known as the standard UNIX epoch,
or simply the epoch.
Mike: What’s Coordinated Universal Time a nd the UNIX epoch ?
Professor: Coordinated Universal Time, or UTC, is the main time standard used to
regulate time a ll over the world. You can think of it simply as time in Lon don when
no daylight savings time is in eec t. UTC replaces Greenwich Mean Time, or GMT,
which is still occasionally u sed as the synonym. The gist of the standard is that the
same date and time in UTC gives precisely the same time instant no m atter where in
the world you are located. Local time is usually given a s an oset from UTC and
depends on the time zone youre in and whether daylight savings time is in eect. For
example, local time in New York is UTC minus ve hours in winter.
8.5. D ate Object 159
An epoch is a moment in time selected as the origin of a particular era an d it provides
a refer ence point from which time is measured. For example, the epo ch of the civil
calendar used internationally is the Inc arnation of Jesus. UNIX is one of the oldest
operating sy stems and the term UNIX epoch is used because it was first defined and
used for the UNIX system. If you are interested, then you may want to check the
www.t imeanddate.com website, which is a great resource of time- and date-related
informa tion.
So this number of milliseconds since mid night on January 1, 1970 is also used inter-
nally b y the Date object to store a single moment in time. For example, if you need a
Date object that is set to one hour past midnight on January 1, 1970 (UTC), you write
the following statement:
var distantPast = new Date(3600000);
Maria: This is a huge number already. How do y ou write modern date s without losing
precision?
Professor: You don’t lose precision that quickly. Reca ll that you can write integers
as large as 9007199254740992 using the 64-bit floating-point representation. If th ese
are milliseconds, that’s more than a hundred million days. To be exact, you can move
in the range from minus to plus 273,785 years since the UNIX epoch. That’s a lot.
Professor: There’s one more constructor in the above example , which allows you
to specify time and date in local time. Note that you don’t have to provide all the
arguments as long as youre omitting them from the right. For example, if you want
to supply hours as an argument, then you should at least supply year, month, and day
as well, while the rest can be omitted :
//March 13, 2017 at 8 p.m. (local time):
var partyTime = new Date(2017, 2, 13, 20);
It is important that you specify hours as an integer from 0 to 23, days from 1 to 31,
and months from 0 to 11.
Mike: It’s weird that days should be counted from one and months from zero.
Professor: As a matter of fact, there’s a good reason for that. You’ll find out why that
is so in the next meeting.
OK, an object is now cre ated but what can you do with it? The Date object has no
properties that ca n be accessed directly. Instead, all reading and writing of time and
date values is do ne through methods, of which they are many, and we will on ly ta ke a
short gla nce at some of them:
getDay() //Returns the day of the week, an integer from zero
//(Sunday) to six (Saturday).
getFullYear() //Returns the year, in four-digit format.
160 Meeting 8. Introducing Objects
getMonth() //Returns the month, an integer from zero (January)
//to 11 (December).
getDate() //Returns the day of the month, an integer from
//one to 31.
getHours() //Returns the hours, an integer from zero (midnight)
//to 23 (11 p.m.).
getMinutes() //Returns the minutes, an integer from zero to 59.
getSeconds() //Returns the seconds, an integer from zero to 59.
getTime() //Returns the internal, millisecond representation
//of the Date object.
toString() //Returns a string representation of time and date.
You can also set all the values, except the day of the week, of course:
setFullYear(...) //Sets the year, and optionally the month and day.
setMonth(...) //Sets the month, and optionally the day of the month.
setDate(...) //Sets the day of the month.
setHours(...) //Sets the hours, and optionally the minutes, seconds
//and milliseconds.
setMinutes(...) //Sets the minutes, and optionally the seconds and
//milliseconds.
setSeconds(...) //Sets the seconds, and optionally the milliseconds.
setTime(...) //Sets time and date using the millisecond format.
Note that all these methods except getTime() and set Time() return and set val-
ues using local time. If you want to set universal time, you c an use any one of
their counterparts, which have an additional “UTC” in their names. For example,
setUTCHours() or getUTCHours().
Maria: That’s a lot of data to remember.
Professor: Don’t even think of remembering all this stu. The important thing is that
you understand th e principles. If you need to set hours, for example, y ou’ll just look
up an appropriate method from the list or, better still, from the language referenc e
such as the one at the end of this book.
Speaking of principles, how do y ou think you can call, for example, the getDate()
method o f the Date object?
Mike: I can use the dot access operator:
dayOfMonth = Date.getDate(); //Wrong: Date is a data type.
Professor: That won’t work. Remember, Date is not a “proper” object but a data type
and you cannot call methods on data types. You need an object instance for that. For
example:
8.5. D ate Object 161
var partyTime = new Date(2017, 2, 13, 20); //Creates an object
//instance.
dayOfMonth = partyTime.getDate(); //Correct: partyTime is a Date
//object instance.
However, there do exist some methods that can be called directly through the Date
object. In contrast to the methods listed above, which are called instance meth ods be-
cause you can call them only through object instances, they are called static methods.
For example:
Date.now() //Static method that returns the millisecond
//representation of the current time. It returned
//1422025494222 at the time of testing these lines.
Date.UTC(2015, 0, 1) //Static method that returns the millisecond
//representation of time and date specified in
//universal time.
We’re now ready for a more practical example. Let’s make a page that will count down
the time to the 2016 Summe r O lympics. This is the algorithm:
Construct two Date objects, one for th e present moment and one for the time
of the opening c eremony. The ceremony will take place on August 5, 2016 at
8 p.m. Brasília time.
If the ope ning ceremony starts in the future Then
Compute the time dierence in milliseconds between both time stamps.
Divide the dierence by 1000 and round down to the nearest integer to get
the number of seconds until the opening ceremony.
Divide the seconds by 86,400 ( = 60 × 60 × 24 ) a nd round down the result
to the nearest integer to get the days.
Divide the remainder of the previous division by 36 00 to get the hours.
Divide the remainder of the previous division by 60 to get the minutes.
The remainder of the previous division are the seconds.
End If
The tricky part is computing the time dierence. I believe that you are bewildered
by all the available Date methods, some operating in local, others in universal time.
In fact, things aren’t that complicated once yo u recognize that internally, time is in-
variably stored using universal time. Lo cal time is only used occasionally when Date
objects interact with the environment. For example, when you call a Date() con-
structor without arguments, it automatically reads th e current time in universal time
disregarding time zone and daylight savings time settings. Wh en you want to get spe-
cific information from the object, you can d o that using local as well as universal time
without having to worry about the conversions.
To keep things under con trol, we’ll calculate the time dierence using u niversal time,
of course. We just discovered that no extra work is needed on our part to convert the
current time from local to universal time. The D ate() constructor doe s it for us.
162 Meeting 8. Introducing Objects
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.118.37.120