Format a date as ISO 8601 in JavaScript
ISO 8601 is the standard format for date-time strings used in APIs and databases — YYYY-MM-DDTHH:MM:SS. JavaScript’s built-in toISOString() always returns UTC. If you need local time in the same format, you have to pad and join the date parts manually.
Problem: Sometimes you need to format a date as ISO 8601 in JavaScript — here's how.
Solution:
function formatDate( date ) {
var d = new Date( date );
var year = d.getFullYear();
var month = String( d.getMonth() + 1 );
var day = String( d.getDate() );
var hours = String( d.getHours() );
var minutes = String( d.getMinutes() );
var seconds = String( d.getSeconds() );
if ( month.length < 2 ) month = '0' + month;
if ( day.length < 2 ) day = '0' + day;
if ( hours.length < 2 ) hours = '0' + hours;
if ( minutes.length < 2 ) minutes = '0' + minutes;
if ( seconds.length < 2 ) seconds = '0' + seconds;
return [year, month, day].join( '-' ) + 'T' + [hours, minutes, seconds].join( ':' );
}
console.log( formatDate( new Date() ) ); // current date in ISO 8601
NOTE: The built-in Date.prototype.toISOString() returns an ISO 8601 string in UTC with a trailing Z. The custom function above uses local time methods (getFullYear, getMonth, etc.) and produces a local datetime string without timezone info. Use toISOString() if you need UTC, or toISOString().slice(0, 19).replace('T', ' ') for a plain UTC datetime string.