Dates

 

7 points

 

Introduction

This program makes use of Javascript's Date class. The Date class reads the computer clock to know what day it is (Monday, etc.), what the date is (e.g. October 4, 2021) and what time it is (e.g. 9:23 a.m.). A Date object can be stored in a variable, for example:

var now = new Date();

The variable 'now' holds the Date information from the exact moment that the statement runs. How can you get access to this information? To extract the current year from 'now' and store it in the variable 'currentYear' you might write:

var currentYear = now.getFullYear()

Here is a list of Date methods:

Method Value Range Description
now.getTime() 0 - ... Milliseconds since 1/1/1970
now.getFullYear() 2021, 2022 ... Year
now.getMonth() 0 - 11 Month (January = 0)
now.getDate() 1 - 31 Date
now.getDay() 0 - 6 Day of week (Sunday = 0)
now.getHours() 0 - 23 Hour of day
now.getMinutes() 0 - 59 Minute of current hour

You can also change the information in a Date object by using SET methods instead of GET methods. For example: now.setFullYear(2025); would change the year stored in 'now' to 2025. Other SET methods include: setTime, setMonth, setDate and setDay.

In this app, you use GET methods with a Date object to find out today's month, date and year. The app then prints out this information for today. You also use GET methods, and IF statements, to print out the day that it is (Monday, etc.).

 

Extra Credit (2 points)

Calculate and print out the month, day and year 1 week from now.

Here is an example from code.org that shows the Date class in action:

// printTime() is a function that formats the time

var nowNJ = new Date();
var minutes = nowNJ.getMinutes();
msg = "New Jersey date & time: \n" + printTime(nowNJ) + "\n";
minutes = minutes + 60;
nowNJ.setMinutes(minutes);
msg = msg + "New Jersey date & time: \n" + printTime(nowNJ) + "\n";
setText("lblResult", msg);

Here is the output from this code:

What this shows is that the Date class is smart. If you add minutes, hours or days to a Date object, the object will adjust correctly.

 

 

Video

The video shows what a completed app should do.