Skip to content

Instantly share code, notes, and snippets.

@progrium
Last active November 20, 2021 04:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save progrium/6b0a6bc1d91a6d297c88ddda25e66acb to your computer and use it in GitHub Desktop.
Save progrium/6b0a6bc1d91a6d297c88ddda25e66acb to your computer and use it in GitHub Desktop.
Intl.DateTimeFormat is kinda nutty with custom format strings, this makes it sane
function dateTimeFormat(timestamp, locale, str, ...opts) {
const d = new Date(timestamp);
return str.replace(/{(\d+)}/g, function(match, number) {
return typeof opts[number] != 'undefined'
? new Intl.DateTimeFormat(locale, opts[number]).format(d)
: match;
});
}
console.log(dateTimeFormat("2021-11-19T19:19:36.598071-06:00", "en", "{0} at {1}!", {dateStyle:"short"}, {timeStyle:"long"}))
// => "11/19/21 at 7:19:36 PM CST!"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment