Skip to content

Instantly share code, notes, and snippets.

@eugenetriguba
Last active June 14, 2021 01:39
Show Gist options
  • Save eugenetriguba/9dbc5705db00866f49244d150d457ba6 to your computer and use it in GitHub Desktop.
Save eugenetriguba/9dbc5705db00866f49244d150d457ba6 to your computer and use it in GitHub Desktop.
Timezone-aware ISO String in JavaScript
$ node
Welcome to Node.js v14.16.1.
Type ".help" for more information.
> const { getTimezoneAwareISOString } = require('./time')
undefined
> getTimezoneAwareISOString()
'2021-06-13T15:42:58.304-05:00'
> new Date().toISOString()
'2021-06-13T20:43:04.271Z'
> getTimezoneAwareISOString(new Date(2020, 11, 15, 12, 15, 12, 100))
'2020-12-15T13:15:12.100-05:00'
/**
* Retrieves the current time or converts a Date into
* an ISO timezone aware string. i.e '2021-06-13T09:22:15.926-05:00'
* By default, new Date().toISOString() would be UTC.
*
* @param {Date|null} date - Optionally, the date to
* convert to a timezone aware ISO string. Otherwise,
* the current time will be used.
*
* @returns {String} A timezone aware ISO date string.
*/
function getTimezoneAwareISOString(date = null) {
let tzOffsetMin = new Date().getTimezoneOffset();
let tzOffsetMs = tzOffsetMin * 60000;
let timeMs = date instanceof Date ? date.getTime() : Date.now();
return new Date(timeMs - tzOffsetMs).toISOString().replace(
'Z',
// A '-' is used here since the offset sign is
// flipped from what we want when we
// getTimezoneOffset(). Ex. UTC+10 => -600
// However, we want +10:00 in the ISO string,
// not -10:00.
convertMinutesToOffset(-tzOffsetMin)
);
}
/**
* Convert minutes to a UTC offset.
*
* @param {Number} minutes - The minutes to convert to an offset.
* @returns {String} A time of the form '+10:00'.
*/
function convertMinutesToOffset(minutes) {
if (minutes === 0) {
return 'Z';
}
let absMinutes = Math.abs(minutes);
let h = Math.floor(absMinutes / 60);
let m = absMinutes % 60;
h = h < 10 ? '0' + h : h;
m = m < 10 ? '0' + m : m;
let hoursMins = h + ':' + m;
return minutes > 0 ? `+${hoursMins}` : `-${hoursMins}`;
}
module.exports = { getTimezoneAwareISOString };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment