Created
September 6, 2022 09:58
-
-
Save Ajnasz/3ce3052384425847f1e869fec8565fd3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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