How to Use toLocaleDateString in JavaScript: Simple Guide
Use
toLocaleDateString() on a JavaScript Date object to convert it into a readable date string formatted according to a specific locale and options. You can pass a locale string like 'en-US' and an options object to customize the output format.Syntax
The toLocaleDateString() method is called on a Date object and can take two optional parameters:
- locale: A string or array of strings that specify the language and region format, e.g.,
'en-US'for US English. - options: An object to customize parts of the date like year, month, day, weekday, etc.
If no parameters are given, it uses the default locale and default formatting.
javascript
dateObj.toLocaleDateString([locale[, options]])
Example
This example shows how to format a date in US English with full weekday and month names, and numeric day and year.
javascript
const date = new Date('2024-06-15T12:00:00Z'); const formattedDate = date.toLocaleDateString('en-US', { weekday: 'long', // full name of the day year: 'numeric', month: 'long', // full name of the month day: 'numeric' }); console.log(formattedDate);
Output
Saturday, June 15, 2024
Common Pitfalls
Some common mistakes when using toLocaleDateString() include:
- Passing invalid locale strings, which causes it to fallback to the default locale silently.
- Expecting consistent output across all browsers without specifying options, as defaults vary by environment.
- Not using the options object to control the format, leading to unexpected date formats.
javascript
const date = new Date(); // Wrong: invalid locale string, fallback to default console.log(date.toLocaleDateString('invalid-locale')); // Right: valid locale and options for consistent format console.log(date.toLocaleDateString('en-GB', { day: '2-digit', month: '2-digit', year: 'numeric' }));
Output
6/15/2024
15/06/2024
Quick Reference
Here are some common options you can use with toLocaleDateString():
| Option | Description | Example Values |
|---|---|---|
| weekday | Name of the day | 'narrow', 'short', 'long' |
| year | Year format | 'numeric', '2-digit' |
| month | Month format | 'numeric', '2-digit', 'narrow', 'short', 'long' |
| day | Day of the month | 'numeric', '2-digit' |
| timeZone | Time zone to use | 'UTC', 'America/New_York', etc. |
Key Takeaways
Use toLocaleDateString() on a Date object to format dates based on locale and options.
Always specify a valid locale string to control language and region formatting.
Use the options object to customize the date parts like year, month, and day.
Defaults vary by browser, so specify options for consistent output.
Invalid locale strings fallback silently to default locale without errors.