Converting a JavaScript date to an ISO date string is a common requirement when you need a standard format for APIs, logs, and database payloads. ISO 8601 is the usual choice because it is predictable and easy to compare.
The main method is toISOString(), but you can also build a custom ISO-like string with template literals when you need a local offset. If you want the source value from a string first, JavaScript date comparison and JavaScript trim are often nearby cleanup steps.
Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.
Method 1: Convert a date with toISOString()
toISOString() returns a UTC-based ISO 8601 string.
const current = new Date("2023-04-18T11:54:22.742Z");
console.log("iso:", current.toISOString());You should see one line logging iso: 2023-04-18T11:54:22.742Z.
Use this when you want a reliable UTC timestamp for APIs and logs.
Method 2: Build a local ISO-like string
A custom format is useful when you need the local timezone offset instead of UTC.
const date = new Date("2023-04-18T11:54:22.742Z");
const isoLike = `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}T${String(date.getHours()).padStart(2, "0")}:${String(date.getMinutes()).padStart(2, "0")}:${String(date.getSeconds()).padStart(2, "0")}`;
console.log("iso-like:", isoLike);You should see one line logging iso-like: 2023-04-18T11:54:22.
This is useful when you want a readable date string without forcing UTC.
Method 3: Use ISO strings in APIs
ISO strings are easy to sort and are a common payload format for APIs.
const createdAt = new Date().toISOString();
console.log("iso-now:", createdAt.includes("T"));You should see one line logging iso-now: true.
Use ISO strings when you want a consistent date format across systems.
Summary
JavaScript date to ISO string conversion is usually done with toISOString(), while template literals help when you need a custom local format. ISO 8601 is the safest choice for APIs, logs, and cross-system date handling.
