Explain Codes LogoExplain Codes Logo

How do I output an ISO 8601 formatted string in JavaScript?

javascript
date-formatting
iso-8601
time-zones
Nikita BarsukovbyNikita BarsukovΒ·Feb 13, 2025
⚑TLDR

To get an ISO 8601 formatted string in JavaScript, use the Date.prototype.toISOString() method:

const isoDateString = new Date().toISOString(); // "YYYY-MM-DDTHH:mm:ss.sssZ" console.log(isoDateString); // Debug Tip: Always "log" your dates, it's free! πŸ˜‰

This method turns the current date and time into a standardized ISO 8601 format, perfect for timestamps and consistent data storage.

Working with Time Zones and UTC

The toISOString() function returns the date in UTC. To produce a valid ISO 8601 date string for a different time zone, you need to account for the timezone offset:

const now = new Date(); const offsetMinutes = now.getTimezoneOffset(); const isoStringWithOffset = new Date(now.getTime() - offsetMinutes * 60000).toISOString(); console.log(isoStringWithOffset); // Double-check your results, trust but verify! πŸ˜‰

Checking Compatibility and Using Polyfills

While toISOString() is widely supported, older browsers may not have it. In such cases, using a polyfill can save the day:

if (!Date.prototype.toISOString) { (function() { function pad(number) { if (number < 10) { return '0' + number; } return number; } Date.prototype.toISOString = function() { return this.getUTCFullYear() + '-' + pad(this.getUTCMonth() + 1) + '-' + pad(this.getUTCDate()) + 'T' + pad(this.getUTCHours()) + ':' + pad(this.getUTCMinutes()) + ':' + pad(this.getUTCSeconds()) + '.' + (this.getUTCMilliseconds() / 1000).toFixed(3).slice(2, 5) + 'Z'; }; }()); }

Manipulating Precision and Custom Formatting

When dealing with toISOString(), keep in mind it's all about precision. Trim excessive precision by slicing the toISOString() output:

const preciseDate = new Date().toISOString().slice(0, 19) + 'Z'; console.log(preciseDate); // "YYYY-MM-DDTHH:MM:SSZ"

Note that you manually appended 'Z' to indicate UTC.

Legacy System Integration

If you're dealing with legacy systems, additional TLC might be necessary. Always validate the date format required and test thoroughly:

const legacyFormat = new Date().toISOString().slice(0, 19); console.log(legacyFormat); // "YYYY-MM-DDTHH:MM:SS" - Ah, simpler times! 🎩

Helpful Libraries at Your Service

Don't forget the utility libraries that can make your life a lot easier. Libraries like Luxon and Day.js can help with advanced time zone handling and precise date manipulation.