JavaScript Date API Worksheet

Questions

This reference may be helpful in understanding how you can work with Date objects.

Question 1

If you invoke the Date constructor without passing in any parameters, what date will be stored in the object that is returned?

If the Date constructor is invoked without passing in any parameters, it will show today's date.

Question 2

What is an 'epoch'?

An epoch marks the occurence of an event.
Some examples of an epoch is 0 B.C. (the date that humans use to keep track of years passed) or January 1st, 1970 (the date that computers use to keep track of time passed).

Question 3

What is a 'Unix timestamp' (also known as 'epoch time')?

A Unix timestamp (or Unix time) is the number of milliseconds that have elapsed since the Unix epoch (as mentioned in the question above, this would be January 1st, 1970). As time passes, the Unix timestamp grows larger and larger.

Question 4

What is the actual date of the epoch for Unix timestamps?

The actual date of the Unix epoch is January 1st, 1970 (at midnight), which starts at 0 milliseconds.

Question 5

What does the getTime() method of a date object return (refer to the link that was mentioned above, or find another reference on the Date object in JavaScript)?

According to the reference linked above, the getTime() method of a date object returns the number of milliseconds since the Unix epoch, the midnight of January 1st, 1970, and a specified date. If there is no specified date, then it would be based off of today's date.

Question 6

If you are working with 2 date objects, how could you use the getTime() method to determine if one date is more recent than the other?

The more recent date object can be determined by finding the difference in milliseconds between the two dates using the getTime() method. If the difference is greater than 0, then the first date listed in the expression is more recent. If the difference is less than 0, then the second date listed is more recent.

For example:
const date1 = new Date(2025, 0, 1);
const date2 = new Date(2024, 0, 1);

let differenceInMS = date1.getTime() - date2.getTime();
console.log(differenceInMS);
// 1st date listed is more recent - "31622400000"

differenceInMS = date2.getTime() - date1.getTime();
console.log(differenceInMS);
// 2nd date listed is more recent - "-31622400000"
			
As a shortcut, you can omit the getTime() method and list let differenceInMS = date1 - date2;.

You can also use comparison operators in an IF statement, which can compare the milliseconds directly to one another. For example:
const date1 = new Date(2025, 0, 1);
const date2 = new Date(2024, 0, 1);

const time1 = date1.getTime();
const time2 = date2.getTime();

if(time1 > time2){
	console.log("date1 is more recent.");
}else{
	console.log("date2 is more recent.");
}
			
In both of the examples above, it has been proven that date1 is the more recent date of the two date objects declared.