In the previous lecture video, you learned how to work with the Date
object in JavaScript. But there are a few different ways to format dates in JavaScript.
In this lecture, we’ll take a look at how to work with the toISOString()
, toString()
, and toLocaleDateString()
methods to format dates in JavaScript.
Before we look at the different methods, let’s first review what the Date
object looks like:
const date = new Date();
console.log(date);
When you log the date
object to the console, you will see the current date and time based on the user’s system settings. Here is an example of the output you might see:
Sun Sep 29 2024 19:45:37 GMT-0700 (Pacific Daylight Time)
If you were to use the toString()
method on the date
object, you would see the same output as above.
To format the date in an extended ISO format (ISO 8601), you can use the toISOString()
method like this:
const date = new Date();
console.log(date.toISOString());
ISO 8601 is an international standard for representing dates and times. The format is YYYY-MM-DDTHH:mm:ss.sssZ
.
The following example will log the current date and time in the ISO 8601 format like this:
2024-09-30T02:47:20.292Z
Another way to format the date, would be to use the toLocaleDateString()
method. This method allows you to format the date based on the user’s locale. Here is the basic syntax for using the toLocaleDateString()
method:
const date = new Date();
console.log(date.toLocaleDateString());
The example output would show the user’s locale date format like this:
9/29/2024
The toLocaleDateString()
method accepts two optional parameters: locales
and options
.
The locales
parameter is a string representing the locale to use. For example, you can pass in en-US
for English (United States) or fr-FR
for French (France). If you don’t pass in a locales
parameter, the default locale is used. Here is an example of how to use the locales
parameter:
const date = new Date();
console.log(date.toLocaleDateString("fr-FR"));
The second optional parameter is the options
parameter. This parameter is an object that allows you to specify the format of the date string. Here is an example of how to use the options
parameter:
const date = new Date();
const options = {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
};
console.log(date.toLocaleDateString("en-GB", options));
In the above example, we specified the options to be in English (Great Britain) and to include the full weekday, year, month, and day. Here is an example of what the output would look like:
Sunday, September 29, 2024
In this video, we have only covered a few of the ways to format dates in JavaScript. There are many other methods and libraries available to help you format dates in JavaScript. But the toISOString()
, and toLocaleDateString()
methods are a good starting point for formatting dates in JavaScript.