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 yourself.
Problem: You need to format a date as ISO 8601 in JavaScript, in local time.
Local time in ISO 8601 format
function formatDate( date ) {
var d = new Date( date );
function pad( n ) {
return n < 10 ? '0' + n : String( n );
}
return d.getFullYear() + '-' + pad( d.getMonth() + 1 ) + '-' + pad( d.getDate() ) +
'T' + pad( d.getHours() ) + ':' + pad( d.getMinutes() ) + ':' + pad( d.getSeconds() );
}
console.log( formatDate( new Date() ) ); // e.g. 2018-04-05T08:30:00
getMonth() counts months from zero, hence the + 1. The pad() helper adds a leading zero to single-digit values. In ES2017 and later you can write String( n ).padStart( 2, '0' ) instead.
Add the time zone offset
A string without a time zone is ambiguous: another system will read it in its own local time. To make it unambiguous, append the offset from UTC, for example +02:00:
function timezoneOffset( date ) {
var offset = -date.getTimezoneOffset(); // minutes, positive east of UTC
var sign = offset >= 0 ? '+' : '-';
offset = Math.abs( offset );
return sign + ( '0' + Math.floor( offset / 60 ) ).slice( -2 ) + ':' + ( '0' + offset % 60 ).slice( -2 );
}
var now = new Date();
console.log( formatDate( now ) + timezoneOffset( now ) ); // e.g. 2018-04-05T08:30:00+02:00
When toISOString() is enough
If you need UTC, use the built-in method. It returns milliseconds and a trailing Z:
new Date().toISOString(); // e.g. 2018-04-05T06:30:00.000Z
For a MySQL DATETIME value in UTC, cut and change it: new Date().toISOString().slice( 0, 19 ).replace( 'T', ' ' ) gives 2018-04-05 06:30:00.