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.
npm run import -- "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;
/**
* 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:
pad(n)
function:
n
and adds a leading zero if it's less than 10. This ensures consistent two-digit formatting for hours, minutes, seconds, etc.ISODateString(d)
function:
d
as input.getUTCFullYear()
, getUTCMonth()
, getUTCDate()
, getUTCHours()
, getUTCMinutes()
, and getUTCSeconds()
to extract the year, month, date, hours, minutes, and seconds from the date object.pad()
function to format each component with leading zeros if necessary.YYYY-MM-DDTHH:mm:ss-00:00
.Export:
module.exports = ISODateString;
line makes the ISODateString
function available for use in other parts of the project or in other modules.Let me know if you have any other code snippets you'd like me to explain!