Last active
July 18, 2020 08:18
-
-
Save ngsctt/e83e65bb02bc24d8f64e3b154dd3cbbc to your computer and use it in GitHub Desktop.
JavaScript function to generate an ISO 8601 or RFC 3339 timestamp. MIT licence.
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 isoTimeStamp(date, options = {}) { | |
console.log(options) | |
let defaults = { | |
date_time: 'T', | |
time_offset: '' | |
} | |
Object.assign(options, Object.assign(defaults, options)); | |
console.log(options) | |
const year = date.getFullYear(); | |
const month = String(date.getMonth()).padStart(2, '0'); | |
const day = String(date.getDate()).padStart(2, '0'); | |
const hour = String(date.getHours()).padStart(2, '0'); | |
const minute = String(date.getMinutes()).padStart(2, '0'); | |
const second = String(date.getSeconds()).padStart(2, '0'); | |
const millisecond = String(date.getMilliseconds()).padStart(3, '0'); | |
const offset = Number(date.getTimezoneOffset()); | |
const offset_sign = offset >= 0 ? '-' : '+'; | |
const offset_hour = String(Math.abs(Math.floor(offset / 60))).padStart(2, '0'); | |
const offset_minute = String(Math.abs(offset % 60)).padStart(2, '0'); | |
return `${year}-${month}-${day}${options.date_time}${hour}:${minute}:${second}.${millisecond}${options.time_offset}${offset_sign}${offset_hour}:${offset_minute}`; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment