A Guide to Working with Dates in JavaScript

JavaScript provides a built-in Date constructor to work with dates and times. It represents time as the number of milliseconds elapsed since the epoch, January 1, 1970, 12:00 UTC.

Creating a date

The Date() constructor returns a date object, and by default, it will be created with the current date and time. For instance,

javascript
1const today = new Date();
2
3console.log(today);
text
12024-05-20T19:15:05.743Z

You can also create a custom date by passing a date string.

javascript
1const date = new Date("2022-03-25");
2
3console.log(date);
text
12022-03-25T00:00:00.000Z

Date formatting

The Date() constructor accepts three types of date strings: ISO date, short date, and long date. Our previous example uses an incomplete ISO format date string. The full ISO date looks like this:

javascript
1const date = new Date("2019-08-25T12:10:26Z");
2
3console.log(date);
text
12019-08-25T12:10:26Z

The date and time are separated with the letter T, and the letter Z indicates we are using the UTC (Universal Time Coordinated) time.

If you wish to customize the timezone, replace Z with the timezone of your choice.

javascript
1const date = new Date("2019-08-25T12:10:26+06:00");
2
3console.log(date);
text
12019-08-25T06:10:26.000Z

The Date() constructor will automatically convert it into UTC time.

The more human-readable formats are also allowed here. For instance, you can use the short date format:

javascript
1const date = new Date("08/21/2020");
2
3console.log(date);
text
12020-08-21T04:00:00.000Z

Or the long date format:

javascript
1const date = new Date("Aug 21 2020");
2
3console.log(date);
text
12020-08-21T04:00:00.000Z

The month can be written in full or abbreviated format.

javascript
1const date = new Date("August 21 2020");
2
3console.log(date);
text
12020-08-21T04:00:00.000Z

However, you should know that even though human-readable formats give us more flexibility when creating dates, it is still not as "smart" as you might wish. You still have to follow a predefined syntax, otherwise it will cause an error.

For instance, the short format needs to be written in MM/DD/YYYY, and the leading zeros should not be omitted.

Other syntaxes, such as YYYY/MM/DD or MM-DD-YYYY, technically work in most cases, but because they are not explicitly defined in the Date() constructor, JavaScript will have to try to "guess" what this syntax means. In some cases, it will return NaN.

javascript
1const date1 = new Date("08/21/2020"); // Use this one
2const date2 = new Date("2020/08/21"); // Works, but not recommended
3const date3 = new Date("08-21-2020"); // Works, but not recommended
4const date4 = new Date("8/21/2020"); // Works, but not recommended
5
6console.log(date1);
7console.log(date2);
8console.log(date3);
9console.log(date4);

As for the long date, you should make sure you are following the syntax Month Date Year. Commas will be ignored in this case.

javascript
1const date1 = new Date("Aug 21 2020");
2const date2 = new Date("August 21 2020");
3const date3 = new Date("August 21, 2020");
4
5console.log(date1);
6console.log(date2);
7console.log(date3);

Getters and setters

There are several getters and setters associated with the date object, allowing you to get or set certain parts of a date. For example, getDate() retrieves the day of the month:

javascript
1const date = new Date("08/21/2020");
2
3console.log(date.getDate());
text
121

getDay() retrieves the day of the week:

javascript
1const date = new Date("08/21/2020");
2
3console.log(date.getDay());
text
15

You can find a full list of date object getters here.

Besides the getters, there are also setters that allow you to modify an existing date. For example, you can use setHours() to set the hour of a date:

javascript
1const date = new Date("08/21/2020");
2
3date.setHours(2);
4
5console.log(date);
text
12020-08-21T06:00:00.000Z

Notice that the time is automatically converted to UTC.

The same setter can also be used to set minutes, seconds, and milliseconds.

javascript
1const date = new Date("08/21/2020");
2
3date.setHours(2, 30, 10, 15);
4
5console.log(date);
text
12020-08-21T06:30:10.015Z

You can find a full list of date object setters here.

Customize output date string

The most common uses for the date object are format and timezone conversion.

For example, when storing dates inside the database, you'll want to be as accurate as possible, so you should use either the ISO representation in UTC time, or the milliseconds representation, which represents the number of milliseconds that have passed since the epoch.

However, these representations are not user-friendly if you use them directly in your application, so instead, you should convert them into a more readable format. For instance,

javascript
1const date = new Date("2022-12-21T13:21:21.300Z");
2
3const options = {
4  weekday: "long",
5  year: "numeric",
6  month: "long",
7  day: "numeric",
8};
9
10console.log(date.toLocaleDateString("en-US", options));
text
1Wednesday, December 21, 2022

The toLocaleDateString() method takes two parameters, <locale> and <options>.

<locale> specifies the language and timezone. In this case, we are using American English, specified by "en-US".

You can also use the <locale> option to define custom calendar ("chinese", "gregory", "persian"), the hour format (12-hour time vs. 24-hour time), the timezone ("Asia/Shanghai", "Asia/Kolkata", "America/New_York"), and so on.

You can find a full list of <locale> options here.

The <options> allows you to define the output format for the date. The accepted values are listed here.

If you need to output the time string as well, you'll need to use toLocaleTimeString(), which accepts similar arguments.

javascript
1const date = new Date("2022-12-21T13:21:21.300Z");
2
3const dateOptions = {
4  weekday: "long",
5  year: "numeric",
6  month: "long",
7  day: "numeric",
8};
9
10const timeOptions = {
11  hour: "2-digit",
12  minute: "2-digit",
13  second: "2-digit",
14  hour12: true, // Change to false for 24-hour format
15  timeZone: "UTC", // Adjust for specific time zones if needed
16};
17
18const formattedDate = date.toLocaleDateString("en-US", dateOptions);
19const formattedTime = date.toLocaleTimeString("en-US", timeOptions);
20
21console.log(`${formattedDate}, ${formattedTime}`);
text
1Wednesday, December 21, 2022, 01:21:21 PM

Using third-party packages to handle dates

As you can see, when it comes to date formatting, plain JavaScript does not have the most user friendly syntax. Not only does it require two separate methods just to output a full date and time string, the options parameter is verbose and not very intuitive for new developers.

In practice, it is often suggested to use a third-party package such as date-fns to handle date formatting.

bash
1npm install date-fns
javascript
1import { format } from "date-fns";
2
3console.log(
4  format(new Date("2022-12-21T13:21:21.300Z"), "EEEE, MMMM do, yyyy hh:mm:ss a")
5);
text
1Wednesday, December 21st, 2022 08:21:21 AM

And this time, you achieve the same result with a single line of code.