Last active
May 26, 2021 11:01
-
-
Save AprilSylph/e12b3e66e9c65e9ba2ab0c741940a324 to your computer and use it in GitHub Desktop.
Create ISO 8601 format date strings in Javascript
This file contains hidden or 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
/** | |
* @param {number} unixTime - seconds elapsed since 1970-01-01T00:00:00.000Z | |
* @returns {string} - ISO 8601 format date, not including milliseconds | |
*/ | |
export const constructISOString = function (unixTime) { | |
const date = new Date(unixTime * 1000); | |
const fourDigitYear = date.getFullYear().toString().padStart(4, '0'); | |
const twoDigitMonth = (date.getMonth() + 1).toString().padStart(2, '0'); | |
const twoDigitDate = date.getDate().toString().padStart(2, '0'); | |
const twoDigitHours = date.getHours().toString().padStart(2, '0'); | |
const twoDigitMinutes = date.getMinutes().toString().padStart(2, '0'); | |
const twoDigitSeconds = date.getSeconds().toString().padStart(2, '0'); | |
const timezoneOffset = date.getTimezoneOffset(); | |
const timezoneOffsetAbsolute = Math.abs(timezoneOffset); | |
const timezoneOffsetIsNegative = timezoneOffset === 0 || Math.sign(timezoneOffset) === -1; | |
const twoDigitTimezoneOffsetHours = Math.trunc(timezoneOffsetAbsolute / 60).toString().padStart(2, '0'); | |
const twoDigitTimezoneOffsetMinutes = Math.trunc(timezoneOffsetAbsolute % 60).toString().padStart(2, '0'); | |
return `${fourDigitYear}-${twoDigitMonth}-${twoDigitDate}T${twoDigitHours}:${twoDigitMinutes}:${twoDigitSeconds}${timezoneOffsetIsNegative ? '+' : '-'}${twoDigitTimezoneOffsetHours}:${twoDigitTimezoneOffsetMinutes}`; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment