Created
September 4, 2023 09:00
-
-
Save KooiInc/b6baddd023847ca2344801c23d0c0584 to your computer and use it in GitHub Desktop.
Create a localized date from stringified date
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
/** | |
* This factory delivers a function to create a date from a | |
* stringified Date (new Date().toString()) without the | |
* offset/locale information. Especially useful for comparison | |
* between dates in different timezones (e.g. client and server). | |
* See https://stackblitz.com/edit/web-platform-ek83hd?file=script.js | |
* for a use case. | |
*/ | |
function localizeStringifiedDateFactory() { | |
const months2Object = (acc, v, i) => ({...acc, [v]: i}); | |
const months = `Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec`.split(`,`).reduce(months2Object); | |
const valueMapper = v => months[v] ?? +v; | |
const getValues = dateStr => dateStr.split(/:|\s/).slice(1, 7).map(valueMapper); | |
const reOrder = values => [values[2], ...values.slice(0, 2), ...values.slice(3)]; | |
const toDateValues = dateStr => reOrder(getValues(dateStr)); | |
return stringifiedDate => new Date(...toDateValues(stringifiedDate)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment