nas5w / javascript-tips-and-tidbits

A continuously-evolving compendium of javascript tips based on common areas of confusion or misunderstanding.
MIT License
1.2k stars 73 forks source link

Date formatting via toLocaleDateString #10

Open nas5w opened 5 years ago

TravisL12 commented 5 years ago

I originally was going to suggest Dates in general within JS but then couldn't think of specific problems that I've come across over the years (how quickly one forgets). Either way, my suggestion using toLocaleDateString could be a subset of a broader Dates category. Such a category could include:

My original comment:

Something that I've found quite useful lately is Date formatting via toLocaleDateString.

If you have a date that you want to format you can use this function in many ways. Example:

const date = new Date();
// Sat Feb 23 2019 20:17:31 GMT-0800 (Pacific Standard Time)

date.toLocaleDateString();
// 2/23/2019

date.toLocaleDateString('en-US', { year: 'numeric', month: 'long' });
// February 2019

date.toLocaleDateString('en-US', { year: 'numeric', month: 'long', weekday: 'long' });
// February 2019 Saturday

// You can use any language localization (i.e. `de-DE`, `es-ES`, etc.)
date.toLocaleDateString('es-ES', { year: 'numeric', month: 'long', weekday: 'long' });
// febrero de 2019 sábado

You can use it to use UTC time as well:
const options = {
    timeZone: 'UTC',
    timeZoneName: 'short',
    weekday: 'long',
    year: 'numeric',
    month: 'long',
    hour:'numeric',
};
date.toLocaleDateString('en-US', options);
// February 2019 Sunday, 4 AM UTC

*/ I'm happy to add more examples */

I'll admit the date options object can get a bit large but I've appreciated this over the confusing strftime formatting.

nas5w commented 5 years ago

I agree Dates need their own section and I really like your outline:

All of your toLocaleDateString examples are good, but I think it's a bit too long because we'll want to include information in the other four subsections without taking up too much real estate. Perhaps the toLocaleDateString section can have the en-US and es-ES examples you already provided, and then a sentence stating how there are many configuration options and a link to some docs (I like MDN).