Time and Date Manipulation
Learn about the UNIX epoch and how to manipulate dates and times.
We'll cover the following...
Working with times and dates can be tricky in programming languages. For this reason, most languages have some sort of built-in Date
object that helps to make the process easier. JavaScript is no exception, and we’ll be taking a look at how that works.
The UNIX epoch
The UNIX epoch is an arbitrary date of January 1, 1970 which is used in programming as a reference point in time from which to measure dates. This allows dates to be expressed as an integer that represents the number of seconds since the epoch. As we can imagine, this produces some very large numbers, and there’s a potential problem looming in 2038 when the number of seconds since the epoch will be greater than
Times and dates
Date
objects contain information about dates and times. Each object represents a single moment in time.
In JavaScript, we can use a constructor function to create a new Date
object using the new
operator. Try entering the following code:
const today = new Date();
The variable today
now points to a Date
object. To see what the date is, we can use the toString()
method that all objects have:
console.log(today.toString());
If an argument isn’t supplied, the date will default to the current date and time based on the system clock and time zone setting. This means that it can be manipulated and shouldn’t be relied on as an accurate representation of the actual date.
It’s possible to create Date
objects for any date by supplying it as an argument to the constructor function. This can be written as a string in a variety of forms, as can be seen in the examples of different holiday dates below:
const christmas = new Date('2021-12-25');// date format is YYYY-MM-DDconsole.log(christmas.toString());const chanukah = new Date('28 November 2021');// First day of Chanukahconsole.log(chanukah.toString());const eid = new Date('Wednesday, May 12, 2021');// Eid-al-Fitrconsole.log(eid.toString());
As we can see, the string passed to the Date
constructor can be in a variety of formats. However, in order to be more consistent, we’d recommend ...