toISOString()
ES5+Returns a string in ISO 8601 format (YYYY-MM-DDTHH:mm:ss.sssZ).
Syntax
date.toISOString()Return Value
A string representing the date in ISO format
Examples
const date = new Date('2024-01-15T14:30:00');
console.log(date.toISOString()); 📌 When to Use
Use toISOString() for API responses, database storage, logs, or any context requiring a standardized, timezone-neutral date format.
⚠️ Common Mistakes
Forgetting that toISOString() always returns UTC time (Z suffix), not local time.
Throwing an error on invalid Date - toISOString() throws RangeError for invalid dates.
✅ Best Practices
Always use toISOString() when sending dates to APIs or storing in databases for consistency.
Wrap in try-catch or validate the date first to handle potential RangeError.
⚡ Performance Notes
toISOString() involves string formatting which is slightly slower than getTime(), but still fast. Prefer caching if called repeatedly for the same date.
🌍 Real World Example
API Date Serialization
Format dates consistently for REST API requests and responses.
function createEventPayload(eventData) {
const now = new Date();
return {
...eventData,
createdAt: now.toISOString(),
updatedAt: now.toISOString(),
scheduledFor: new Date(eventData.scheduledFor).toISOString(),
metadata: {
timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
localTime: now.toLocaleString()
}
};
}
const payload = createEventPayload({
title: 'Team Meeting',
scheduledFor: '2024-03-20T14:00:00'
});
console.log(JSON.stringify(payload, null, 2));
// {
// "title": "Team Meeting",
// "createdAt": "2024-03-15T08:30:00.000Z",
// "updatedAt": "2024-03-15T08:30:00.000Z",
// "scheduledFor": "2024-03-20T14:00:00.000Z",
// ...
// }