A unified way to create dates through the Date object

ProgrammingJun 2021

Like the Math object, the Date object is a built-in object in Javascript that provides a standardized way to create a date in Javascript. Since culturally we have dozens of ways to express a date and time, the Date object is a useful way to put all these together in one single interface and convention.

There are four main ways to create an instance of the Date object: current date-time, a specific date-time in the past or the future, through milliseconds, and last but not least, the give-me-anything and I’ll turn it into a date.

Given that the date then exists in the form of a Javascript object, the Date object also comes with methods that can be used to turn a particular instance of the date into a string of text; as well as to access specific portions of the date like the month, day, day-of-the-week; or even to adjust the date and time expressed.

Creating a date

In its simplest form, the Date object instantiates the current date-time, based on the browser’s location.

Specific date-time allows for the creation of a specific date down to the minute and second.

The millisecond way will instantiate a Date object X milliseconds after January 1 1970. So in the example below, it catapulted us to the year 2231.

Lastly, in written form the date can be complete or incomplete and the format is fairly permissive. Month and year, no day, day of the week…

Useful Methods

First, these methods allow the programmer to translate the object into a human-readable string.

Then we have getter and setter methods. Below are some of the methods that can be used to have granular access to certain portions of the Date object.

Lastly, setter methods provide the ability to change the date after it was instantiated.

A Useful Example

Aside from the self-evident use case of using the Date object to, for example, mark the date-time this post was originally written in, it can also be used to determine how long a particular computer takes to execute a procedure. Useful in the realms of optimization and good programming.

No items found.