To render the "title" portion of an ISO 8601 formatted string, consider utilizing the following approaches:
JavaScript's Date object provides the toISOString() method, which directly returns a string in the ISO 8601 format.
const date = new Date(); const isoString = date.toISOString();
If toISOString() is unavailable, you can implement a custom function to generate ISO 8601 strings:
function isoDate(msSinceEpoch) { const d = new Date(msSinceEpoch); return ( d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1).toString().padStart(2, 0) + '-' + d.getUTCDate().toString().padStart(2, 0) + 'T' + d.getUTCHours().toString().padStart(2, 0) + ':' + d.getUTCMinutes().toString().padStart(2, 0) + ':' + d.getUTCSeconds().toString().padStart(2, 0) ); } console.log(isoDate(Date.now()));
For browsers without support for toISOString(), you can use the following polyfill:
if (!Date.prototype.toISOString) { (function() { function pad(number) { const r = String(number); if (r.length === 1) { r = '0' + r; } return r; } Date.prototype.toISOString = function() { return ( this.getUTCFullYear() + '-' + pad(this.getUTCMonth() + 1) + '-' + pad(this.getUTCDate()) + 'T' + pad(this.getUTCHours()) + ':' + pad(this.getUTCMinutes()) + ':' + pad(this.getUTCSeconds()) + '.' + String((this.getUTCMilliseconds() / 1000).toFixed(3)).slice(2, 5) + 'Z' ); }; })(); }
The above is the detailed content of How to Generate ISO 8601 Formatted Strings in JavaScript?. For more information, please follow other related articles on the PHP Chinese website!