JS Dates

JavaScript Dates: A Beginner's Guide

In order to work with dates and times in JavaScript, we use the built-in Date object. This powerful object comes with many methods and constructors to create, format, and manipulate dates.


1. Creating Date Objects

There are several different ways to create a new date object. Let's explore the most common constructors.

Method 1: new Date()

The simplest way to create a date is to call new Date() with no arguments. This will create a Date object containing the current date and time according to the user's system.

Get Current Date and Time

let currentDateTime = new Date();
console.log(currentDateTime);

Method 2: Date.now()

There is a static built-in method, Date.now(), that returns the current date and time represented as the number of milliseconds since January 1st, 1970 UTC. This arbitrary date is known as the Unix epoch.

Get Milliseconds Since Epoch

let now2 = Date.now();
console.log(now2);

Method 3: new Date(milliseconds)

You can create a specific date by passing a number of milliseconds into the constructor. This will create a date that is that many milliseconds after the Unix epoch.

Date from Milliseconds

// Create a date for 1000 milliseconds (1 second) after the epoch
let milliDate = new Date(1000);
console.log(milliDate); // 1970-01-01T00:00:01.000Z

Method 4: new Date(dateString)

JavaScript can also convert many different string formats into a Date object.

Note: Be careful when using date strings. The order of days and months can vary depending on the user's region and browser settings (e.g., MM/DD/YYYY vs. DD/MM/YYYY), which can lead to unexpected results.

Date from String

let stringDate = new Date("Sat Jun 05 2021 12:40:12 GMT+0200");
console.log(stringDate);

Method 5: new Date(year, month, day, ...)

Finally, you can specify a precise date and time by passing the individual components as arguments to the constructor.

Very Important: The month parameter is 0-indexed in JavaScript! This means January is 0, February is 1, March is 2, and so on, up to December which is 11. This is a very common source of bugs for beginners.

Specific Date Example

// new Date(year, month, day, hours, minutes, seconds, ms)
// Here, month '1' means February!
let specificDate = new Date(2022, 1, 10, 12, 10, 15, 100);
console.log(specificDate); // 2022-02-10T11:10:15.100Z (adjusts for timezone)

Exercise

?

If you create a date using new Date(2024, 0, 1), which month will it represent?