Created
September 6, 2022 08:55
-
-
Save Meldiron/ffba8411f18fd344351951ae860fc995 to your computer and use it in GitHub Desktop.
Methods for converting dates between input type="datetime-local" and server-acceptable ISO 8610 format with timezone awareness.
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 prefixWithZero(value, minLength = 2) { | |
value = value + ""; | |
while (value.length < minLength) { | |
value = `0${value}`; | |
} | |
return value; | |
} | |
function isoToLocal(isoTime) { | |
const date = new Date(isoTime); | |
const localTime = `${date.getFullYear()}-${prefixWithZero(date.getMonth() + 1)}-${prefixWithZero(date.getDate())}T${prefixWithZero(date.getHours())}:${prefixWithZero(date.getMinutes())}:${prefixWithZero(date.getSeconds())}.${prefixWithZero(date.getMilliseconds(), 3)}`; | |
return localTime; | |
} | |
function localToIso(localTime) { | |
const date = new Date(localTime); | |
const isoTime = `${date.getUTCFullYear()}-${prefixWithZero(date.getUTCMonth() + 1)}-${prefixWithZero(date.getUTCDate())}T${prefixWithZero(date.getUTCHours())}:${prefixWithZero(date.getUTCMinutes())}:${prefixWithZero(date.getUTCSeconds())}.${prefixWithZero(date.getUTCMilliseconds(), 3)}+00:00`; | |
return isoTime; | |
} | |
const isoTime = '2022-09-06T12:00:00.000+00:00'; | |
const local = isoToLocal(isoTime); // 2022-09-06T14:00:00.000 | |
const iso = localToIso(local); // 2022-09-06T12:00:00.000+00:00 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment