Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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.2025

The 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, 2025

A 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-05

Common 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 2025

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.