Created
February 4, 2023 10:18
-
-
Save azder/65849cba3afd0f9097b33f56bc4a2cd9 to your computer and use it in GitHub Desktop.
convert Date object to ISO string with zone info
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
const n = $ => Number.isNaN($); | |
const p = $ => { | |
if ($ < 1) { | |
return '00'; | |
} | |
if ($ < 10) { | |
return '0' + $; | |
} | |
return '' + $; | |
}; | |
const q = $ => { | |
if ($ < 1) { | |
return '000'; | |
} | |
if ($ < 10) { | |
return '00' + $; | |
} | |
if ($ < 100) { | |
return '0' + $; | |
} | |
return '' + $; | |
}; | |
// @see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toISOString | |
const zonedIso = (date) => { | |
// | |
if (!(date instanceof Date)) { | |
return ''; | |
} | |
// first part | |
const Y = date.getFullYear(); | |
const M = date.getMonth() + 1; | |
const D = date.getDate(); | |
if (n(Y) || n(M) || n(D)) { | |
return ''; | |
} | |
// T part | |
const h = date.getHours(); | |
const m = date.getMinutes(); | |
const s = date.getSeconds(); | |
// . part | |
const k = date.getMilliseconds(); | |
if (n(h) || n(m) || n(s) || n(k)) { | |
return ''; | |
} | |
// Z part | |
const tzo = -date.getTimezoneOffset(); | |
const abs = Math.abs(tzo); | |
if (n(tzo)) { | |
return ''; | |
} | |
const tzs = tzo >= 0 ? '+' : '-'; | |
const tzh = Math.floor(abs / 60); | |
const tzm = abs % 60; | |
// fragments | |
const dateFragment = `${p(Y)}-${p(M)}-${p(D)}`; | |
const timeFragment = `${p(h)}:${p(m)}:${p(s)}.${q(k)}`; | |
const zoneFragment = `${tzs}${p(tzh)}:${p(tzm)}`; | |
// | |
return `${dateFragment}T${timeFragment}${zoneFragment}`; | |
}; | |
const now = zonedIso(new Date()); | |
console.log(now, '.length:', now.length); | |
console.log(zonedIso()); | |
console.log(zonedIso(new Date(NaN))); | |
console.log(zonedIso(new Date('2222-03-31'))); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment