Skip to content

Instantly share code, notes, and snippets.

@Ajnasz
Created September 6, 2022 09:58
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Ajnasz/3ce3052384425847f1e869fec8565fd3 to your computer and use it in GitHub Desktop.
Save Ajnasz/3ce3052384425847f1e869fec8565fd3 to your computer and use it in GitHub Desktop.
function getDateFields(plainDateTime, locale='en-US') {
const formatter = new Intl.DateTimeFormat(locale, {
year: 'numeric', month: 'numeric', day: 'numeric',
hour: 'numeric', minute: 'numeric', second: 'numeric',
weekday: 'long',
timeZoneName: 'short',
dayPeriod: 'short',
hour12: false,
});
return formatter
.formatToParts(plainDateTime)
.reduce((result, { type, value }) => {
if (type !== 'literal') {
result[type] = value;
}
return result;
}, {});
}
function dateFormat(date, locale = 'en-US') {
const fields = getDateFields(date, locale);
return (strings) => {
return strings.reduce((out, str) => {
return str.replace(/%\{(year|month|day|hour|minute|second)\}/g, (match, name) => {
if (name in fields) return fields[name];
return name;
})
}, '');
}
}
const formatter = dateFormat(new Date(), 'hu-HU');
console.log(formatter`%{year}-%{month}-%{day} %{hour}:%{minute}:%{second}`)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment