Friday, June 27, 2014

JavaScript Print Date in YYYY-MM-DD HH:mm:ss Format With Leading Zeros

Printing out a JavaScript date with leading zeros is a bit more complex than it should be.

var now = new Date();
var dateToPrint = now.getFullYear() + '-' + ('0' + (now.getMonth() + 1)).slice(-2) + '-' + ('0' + now.getDate()).slice(-2) + ' ' + ('0' + (now.getHours() + 1)).slice(-2) + ':' + ('0' + now.getMinutes()).slice(-2) + ':' + ('0' + now.getSeconds()).slice(-2);

The .slice(-2) method allows us to add a leading "0" to every date (including those already containing two characters) and then slice out the last two.

For example, if it is 1PM, the time is 13 (getHours() + 1), but then written as 013, then sliced to 13.

1 comment: