Created
May 23, 2021 15:40
-
-
Save jawj/5a0a8dbad4b86578e53fff1970a0e266 to your computer and use it in GitHub Desktop.
Convert between 6dp ISO8601-format dates and Unix epoch microseconds in Zapatos
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
import { DateString, strict } from 'zapatos/db'; | |
/** | |
* Convert a `DateString` (to 6dp) to microseconds since 1 January 1970. | |
* Nullability is preserved (e.g `DateString | null` becomes `number | null`) | |
* using `strict`. Note: only dates before 5 June 2255 can be represented | |
* within `Number.MAX_SAFE_INTEGER` this way. | |
*/ | |
export const toUnixMicroseconds = strict((d: DateString) => { | |
const | |
us = Date.parse(d) * 1000, | |
uMatch = d.match(/[.]\d{3}(\d{3})([-+][\d:]+|Z|)$/), | |
uAddition = uMatch ? parseInt(uMatch[1], 10) : 0; | |
return us + uAddition; | |
}); | |
/** | |
* Convert microseconds since 1 January 1970 to a `DateString`. Nullability is | |
* preserved (e.g `number | null` becomes `DateString | null`) using `strict`. | |
* Note: only dates before 5 June 2255 can be represented within | |
* `Number.MAX_SAFE_INTEGER` this way. | |
*/ | |
export const fromUnixMicroseconds = strict((microseconds: number) => { | |
const | |
us = Math.floor(microseconds), | |
ms = Math.floor(us / 1000), | |
uStr = String(us - ms * 1000), | |
uPadded = '00'.slice(uStr.length - 1) + uStr, | |
iso = new Date(ms).toISOString(), | |
tz = iso.match(/[.]\d{3}(|Z|[-+][\d:]+)$/)![1]; | |
return iso.slice(0, iso.length - tz.length) + uPadded + tz as DateString; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment