Skip to content

Instantly share code, notes, and snippets.

@sagirk
Last active August 24, 2018 03:11
Show Gist options
  • Save sagirk/b24f1ba7bd5f37758ed169cab01efdb1 to your computer and use it in GitHub Desktop.
Save sagirk/b24f1ba7bd5f37758ed169cab01efdb1 to your computer and use it in GitHub Desktop.
Utility to manually parse a time string (in the ISO 8601 format) back to a Date object
const utilities = {
/**
* Manually parse a time string back to a Date object.
* Read the following to understand why Date.parse() cannot be relied upon:
* https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/parse
* https://stackoverflow.com/a/20463521
*
* @param {string} time - The time to be parsed in the ISO 8601 format.
* @returns {Date}
*/
parseTime: function parseTime(time) {
// Match time in the ISO 8601 format `YYYY-MM-DDTHH:mm:ssZ` and remember it
const timeFormat = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})Z$/;
const [, year, month, day, hours, minutes, seconds] = timeFormat.exec(time);
// Month is 0-indexed
const monthIndex = month - 1;
const parsedTime = new Date(year, monthIndex, day, hours, minutes, seconds);
return parsedTime;
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment