Question

In my application the dates are stored in ISODate format:

ISODate("2012-04-21T07: 32: 16.285Z")

What would be the simplest wat to just have a string like this:

21/04/2012, 07:32:16

Était-ce utile?

La solution

I like this script http://jacwright.com/projects/javascript/date_format

var d = new Date('2012-04-21T07: 32: 16.285Z'.split(' ').join('')), date;
date = d.format('d/m/Y h:i:s');
console.log(date);

UPD: For IE < 9 you should normalize date - http://delete.me.uk/2005/03/iso8601.html

Autres conseils

If you don't need the zero padding, you can do this:

var d = new Date("2012-04-21T07:32:16.285Z");

var formattedDate = d.getUTCDate() + '/' 
    + (d.getUTCMonth() + 1) + '/' 
    + d.getUTCFullYear() + ', ' 
    + d.getUTCHours() + ':' 
    + d.getUTCMinutes() + ':' 
    + d.getUTCSeconds();

// formattedDate is "21/4/2012, 7:32:16"

Otherwise you could do something like

// zero-pad a two digit integer
function zp(n) {
  return (n > 9 ? '' : '0') + n;
}

var d = new Date("2012-04-21T07:32:16.285Z");

var formattedDate = zp(d.getUTCDate()) + '/' 
    + zp(d.getUTCMonth() + 1) + '/' 
    + d.getUTCFullYear() + ', ' 
    + zp(d.getUTCHours()) + ':' 
    + zp(d.getUTCMinutes()) + ':' 
    + zp(d.getUTCSeconds());

// formattedDate is "21/04/2012, 07:32:16"
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top