Dates and Timestamps

new Date() is the current moment, as an object. getHours(), getMinutes() and getSeconds() read its parts in the device's own time zone.

Date.now() is the same moment as a single number: the milliseconds since the first of January 1970. That number is called a timestamp, and it makes time arithmetic simple. Five minutes from now is Date.now() + 5 * 60 * 1000, and the gap between two moments is one subtraction.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Work out the timestamp for 90 minutes from now, then print how many whole minutes are left until then, using Math.round.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

A clock shows 09:05:07, not 9:5:7, so every number needs two digits. String(n).padStart(2, "0") adds zeros on the left until the text is two characters long. To turn a number of seconds into a display, split it up: Math.floor(s / 3600) hours, Math.floor(s % 3600 / 60) minutes, and s % 60 seconds.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Change clock so it leaves the hours off when there are none: clock(65) should give 01:05, while clock(3725) still gives 01:02:05.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

◈ Graded Build

Write timerDisplay(seconds). It returns MM:SS for anything under an hour and HH:MM:SS from an hour up. A countdown should never show 00:00 while time is still left, so round fractions of a second UP: 0.4 seconds shows 00:01.

Checked by using your page: clicking, typing and waiting, then reading what changed. 5 visible and 2 hidden checks.

loading editor…

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Time Zones with Intl →
← Back