Convert date to ISO 8601 in JavaScript
Problem: Sometime need get format date as ISO 8601 in JavaScript how we can do it?
Solution: If we need get date as ISO 8601 format in JavaScript, we can use next code:
function formatDate( date ) {
var d = new Date( date );
var year = d.getFullYear();
var month = '' + (d.getMonth() + 1);
var day = '' + d.getDate();
var hours = '' + d.getHours();
var minutes = '' + d.getMinutes();
var seconds = '' + d.getSeconds();
if ( month.length < 2 ) month = '0' + month;
if ( day.length < 2 ) day = '0' + day;
var date = [year, month, day].join( '-' );
var time = [hours, minutes, seconds].join( ':' );
return date + 'T' + time;
}
console.log( formatDate( new Date() ) ); // Get current date in ISO 8601