Skip to content

Instantly share code, notes, and snippets.

@mstudio
Last active April 19, 2022 15:28
Show Gist options
  • Save mstudio/1d57356d90815cdf5a56ed873d41ce6d to your computer and use it in GitHub Desktop.
Save mstudio/1d57356d90815cdf5a56ed873d41ce6d to your computer and use it in GitHub Desktop.
Converts a Javascript UTC date string into the proper format for ICS calendar files for DTSTAMP, DTSTART and DTEND
/**
* Converts a UTC date into the proper format for ICS calendar files for DTSTAMP, DTSTART and DTEND
* @param {String} isoDateString, e.g. new Date().toISOString()
* @returns {String} formatted as UTC date for ICS files, e.g. 20220511T170000Z
*/
const toICSDateFormat = (isoDateString) => {
const dateArray = isoDateString.split("T");
const day = dateArray[0].replace(/-/g, "");
const time = dateArray[1].replace(/[a-zA-Z]+/g, "").split(":");
const ics = `${day}T${getDigits(time[0])}${getDigits(time[1])}${getDigits(
time[2],
)}Z`;
return ics;
};
/**
*
* @param {String} timeString, e.g. '2.19'
* @returns {String} 2 digit string, e.g. '02'
*/
const getDigits = (timeString) => {
let digits = String(Math.round(parseInt(timeString, 10)));
if (digits.length === 1) digits = `0${digits}`;
return digits;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment