Today I Learned - Rocky Kev

TIL toLocaleDateString that's built into Javascript for dates

POSTED ON:

TAGS:

Using Date.prototype.toLocaleDateString

Also reconsider using MomentJS for dates. It's a big boi.

The toLocaleDateString() method returns a string with a language sensitive representation of the date portion of this date. The new locales and options arguments let applications specify the language whose formatting conventions should be used and allow to customize the behavior of the function. In older implementations, which ignore the locales and options arguments, the locale used and the form of the string returned are entirely implementation dependent.

toLocaleDateString(locales, options) - MDN

// Initial Use
const date = new Date().toLocaleDateString('en-US');
console.log(date); // 6/18/2021


// Get Formatted Date
const date = new Date().toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric'
});
console.log(date); // June 18, 2021


// Get Date and Time
const date = new Date().toLocaleDateString('en-US', {
hour: 'numeric',
minute: 'numeric'
});
console.log(date); // 6/18/2021, 10:30 AM

// Get Formatted Date and Time
const date = new Date().toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric'
});
console.log(date); // June 18, 2021, 10:30 AM


// Get Formatted Date and Time Including Seconds
const date = new Date().toLocaleDateString('en-US', {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
});
console.log(date); // June 18, 2021, 10:30:54 AM

// Get Formatted Date and Time Including Weekday
const date = new Date().toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric'
});
console.log(date); // Friday, June 18, 2021, 10:30:52 AM

Related TILs

Tagged:

TIL toLocaleDateString that's built into Javascript for dates

Date().toLocaleDateString('en-US') returns a string with a language sensitive representation of the date portion of this date.

TIL toLocaleDateString that's built into Javascript for dates

Date().toLocaleDateString('en-US') returns a string with a language sensitive representation of the date portion of this date.

TIL toLocaleDateString that's built into Javascript for dates

Date().toLocaleDateString('en-US') returns a string with a language sensitive representation of the date portion of this date.