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?

The current date according to local time.

Question 2

What is an 'epoch'?

A notable or significant moment in time.

Question 3

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

The amount of time, in milliseconds, that has passed since midnight, January 1st, 1970.

Question 4

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

See above.

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)?

It returns the amount of milliseconds that have passed since epoch time.

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?

Depends on the definition of 'recent'. If we're going with the definition of which one is further along in time, i.e. 1999 is more recent than 1989, then just measure which date is greater:
`${date1.getTime()>date2.getTime() ? date1.toDateString : date2.toDateString} is more recent.`
Otherwise, if you're going with the definition of recent that is closer to the present, i.e. yesterday is more recent than 100 years from now, then you would want to create a date object representing today, then compare the two objects to that object the same way we did before, except here, you would be wanting to find the smallest difference, like so:

			//just example code
			const recent = (date1, date2) => {
				const today = new Date();
				const diff1 = Math.abs(today.getTime() - date1.getTime());
				const diff2 = Math.abs(today.getTime() - date2.getTime());
				const diff = diff1 > diff2 ? date2 : date1;
				return diff;
			}