Created
May 12, 2020 22:33
-
-
Save spatialtime/f1fe97d30f5104f6c6916a99be7d9f4c to your computer and use it in GitHub Desktop.
JavaScript code for extracting ISO 8601 dates/time fields from a JavaScript Date object.
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
// Passing a string to new Date() is cross-implementation-safe only if the | |
// format of the string conforms to ECMAScript's specified format. | |
// From the specification (https://tc39.es/ecma262/#sec-date.parse): | |
// " If the String does not conform to that format the function may fall | |
// back to any implementation-specific heuristics or implementation-specific date formats. " | |
// As such, we are good to go here with passing it a correct ISO 8601 date/time string. | |
let d = new Date("2020-04-02T13:00:00.000Z") | |
// The beauty of a fixed-width ISO 8601 output string. | |
// It is a breeze to extract any given date/time field. | |
// isoDateTime will be formatted as: YYYY-MM-DDTHH:mm:ss.sssZ | |
let isoDateTime = d.toISOString() | |
let isoYear = isoDateTime.substr(0,4) // "2020" | |
let isoYearMonth = isoDateTime.substr(0,7) // "2020-04" | |
let isoDate = isoDateTime.substr(0,10) // "2020-04-02" | |
let isoHourMinute = isoDateTime.substr(11,5) // "13:00" | |
let isoTime = isoDateTime.substr(11) // "13:00:00.000Z" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment