There's an easy way to format human-readable dates
Dates are hard. They’re SUPER hard when you’re trying to display them to people based on where those people are located.
When working with dates in Javascript, the temptation is often to npm install moment --save
and start looking up momentjs
format strings.
Thanks, again, to MDN web docs, I found an easy and fairly well-supported way to display dates to users in any language.
Using Date.toLocaleString
(and it’s sibling, toLocaleDateString
, it’s pretty easy to display dates that are readable by humans, like February 20, 2019
.
Example
Test for browser support
Not all browsers support the locales
and options
parameters, so it’s a good idea to check for this.
function toLocaleStringSupportsLocales() {
try {
new Date().toLocaleString('i');
} catch (e) {
return e instanceof RangeError;
}
return false;
}
Display a human readable date
If the current environment supports toLocaleDateString
options, the following will return a string
that looks like February 20, 2019
.
const toHumanDate = date => {
date = new Date(date);
if (!toLocaleStringSupportsLocales()) {
// Fall back to using default `toDateString` for the
// current locale.
return date.toDateString();
}
return date.toLocaleDateString('en-US', {
day: 'numeric',
month: 'long',
year: 'numeric',
});
};