How to format a date
Short answer
The toLocaleDateString() method formats a date using the rules of a given language. Months in the Date constructor count from zero, so 2 is March:
const date = new Date(2025, 2, 15);
console.log(date.toLocaleDateString('ru-RU'));Output:
15.03.2025The month name
The second argument controls which parts of the date to show and how:
const date = new Date(2025, 2, 15);
console.log(date.toLocaleDateString('en-US', { day: 'numeric', month: 'long', year: 'numeric' }));Output:
March 15, 2025A custom format
You can read the parts of a date separately and build the string by hand:
const date = new Date(2025, 2, 5);
const day = String(date.getDate()).padStart(2, '0');
const month = String(date.getMonth() + 1).padStart(2, '0');
console.log(date.getFullYear() + '-' + month + '-' + day);Output:
2025-03-05Common mistake
getMonth() counts months from zero, so add one when formatting. And getYear() is an old method that returns the year minus 1900:
const date = new Date(2025, 2, 5);
console.log(date.getMonth(), date.getMonth() + 1);
console.log(date.getYear(), date.getFullYear());Output:
2 3
125 2025Functions used in this recipe
- Date.prototype.toLocaleDateString — Formats a date without time by language rules.
- Intl.DateTimeFormat — Formats dates and times by language rules.
- String.prototype.padStart — Pads a string on the left to a given length.