dates | find Tuesdays late in the month | sum a list of events | Search

This code provides a function ISODateString that converts a Date object into a standardized ISO 8601 formatted string, ensuring consistent date and time representation. It utilizes helper functions and UTC methods to achieve this conversion.

Run example

npm run import -- "Convert a date to ISO"

Convert a date to ISO

function ISODateString(d) {
    function pad(n) {
        return n < 10 ? '0' + n : n
    }

    return d.getUTCFullYear() + '-'
        + pad(d.getUTCMonth() + 1) + '-'
        + pad(d.getUTCDate()) + 'T'
        + pad(d.getUTCHours()) + ':'
        + pad(d.getUTCMinutes()) + ':'
        + pad(d.getUTCSeconds()) + '-00:00';
};
module.exports = ISODateString;

What the code could have been:

/**
 * Converts a Date object to an ISO 8601 formatted string.
 *
 * @param {Date} date - The date to be converted.
 * @returns {string} The ISO 8601 formatted string.
 */
function isoDateString(date) {
    // Use a reusable function to pad the date components
    const pad = n => (n < 10? '0' + n : n);

    // Use template literals for better readability
    return `${date.getUTCFullYear()}-${pad(date.getUTCMonth() + 1)}-${pad(date.getUTCDate())}T`
        + `${pad(date.getUTCHours())}:${pad(date.getUTCMinutes())}:${pad(date.getUTCSeconds())}-00:00`;
}

// Export the function as a module
module.exports = isoDateString;

This code defines a function ISODateString that converts a Date object into an ISO 8601 formatted string.

Here's a breakdown:

  1. pad(n) function:

  2. ISODateString(d) function:

  3. Export:

Let me know if you have any other code snippets you'd like me to explain!