Date Objects!
Goals:
- Access system time using the Javascript Date object.
- Learn more about the Javascript Object data type.
Coding Snippets:
- Create an object representing the current date and time by calling the
Date
constructor with no arguments. - Create an object representing a specific date by passing numeric year, month, and day arguments to the
Date
constructor. Note: the month argument is zero based. - Use dot notation to call functions which provide information about a Date object.
Math and Computer Concepts:
- Javascript includes several built-in object types, such as
Array
andDate
. Pencil Code adds more, such asTurtle
andSprite
. - Objects differ from other data types, such as Number and String, in that they can store collections of different data types in a single unit. For example, Turtle objects store information about a specific turtle's size, color, location, and orientation.
- As with Turtle objects, information about a specific Date object can be accessed via functions, a few of which are listed above. The
Date
constructor also accepts additional arguments. Look up an online code reference for the Date object, such as at w3Schools.com, to explore other features of this useful object.
Activities:
Save each of the following in a folder called Objects.
- Make a copy of your AnalogClockFace program and transform it into a CorrectlySetClock. Use sprites for the clock's hands, turning them to the correct angles using values from a
Date
object. - Convert CorrectlySetClock into a working AnalogClock, complete with second hand. Make it keep time by setting
speed Infinity
and usingpause 1
to keep track of passing of seconds, adjustings the clock hands accordingly. - Program a
BetterAnalogClock
that keeps time more accurately, using frequent calls to system time: create updatedDate
objects every tenth of a second, and useturnto
to point sprites forhourHand
,minuteHand
, andsecondHand
in the correct direction. - Create a DigitalTimeStamp program that shows the current time when run. Note that for 1:03 pm, the Date object functions
getHours
andgetMinutes
will return hour and minute values 13 and 3, so if you simply concatenate the strings, you will show a time of 13:3. Avoid this by using conditional logic to get the correct number of digits for minutes. Also, show am/pm instead of "military time". - Code a ProgramTimer that determines how long a block of code takes to run, printing the result to the screen. You will need two Date objects, one created before and one after the measured program.