Javascript y por lo tanto node.js no proveen de funciones potentes para formatear una fecha. La siguiente función para formatear una fecha quizá os facilite la vida.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | /* parámetro fstr: %Y - año , %m - mes, %d - día, %H - hora, %M - minuto, %S - segundo parámetro utc: true, calcula la fecha y hora local */ Date.prototype.format = function(fstr, utc) { var that = this; utc = utc ? 'getUTC' : 'get'; return fstr.replace (/%[YmdHMS]/g, function (m) { switch (m) { case '%Y': return that[utc + 'FullYear'] (); case '%m': m = 1 + that[utc + 'Month'] (); break; case '%d': m = that[utc + 'Date'] (); break; case '%H': m = that[utc + 'Hours'] (); break; case '%M': m = that[utc + 'Minutes'] (); break; case '%S': m = that[utc + 'Seconds'] (); break; default: return m.slice (1); } return ('0' + m).slice (-2); }); }; |
Demo:
1 2 3 4 5 6 7 8 9 10 11 | a = new Date(); console.log(a.format ("%Y-%m-%d %H:%M:%S", true) ); console.log(a.format ("%d/%m/%Y %H:%M:%S", true)); console.log(a.format ("%d/%m/%Y %H:%M:%S", false)); console.log(a.format ("%m", true) ); console.log(a.format ("%d", true) ); 2013-05-22 19:40:27 22/05/2013 19:40:27 22/05/2013 21:40:27 05 22 |