Christophe Martin
Christophe Martin

Reputation: 223

Javascript convert timestamp

I have a date in this format "2012-12-20 21:34:09".
How to format in the format dd/mm/yyyy

Upvotes: 1

Views: 2307

Answers (5)

jJ'
jJ'

Reputation: 3078

using the power of RegExp it becomes quite simple:

"2012-12-20 21:34:09".replace(/^(\d+)-(\d+)-(\d+).*/, '$3/$2/$1');

returns "20/12/2012"

Upvotes: 0

Lee Taylor
Lee Taylor

Reputation: 7984

None of the other answers handle zero padding, which means that they won't fit the dd/mm/yyyy format for other dates.

var date = new Date("2012-12-20 21:34:09");

var converted = String("0" + date.getDate()).slice(-2);
converted += "/" + String("0" + date.getMonth()+1).slice(-2);
converted += "/" + date.getFullYear();

alert(converted);

Edit

cross-browser version:

var parts = "2012-12-20 21:34:09".split(" ")[0].split("-");

var converted = String("0" + parts[1]).slice(-2);
converted += "/" + String("0" + parts[2]).slice(-2);
converted += "/" + parts[0];

alert(converted);

Upvotes: 0

jeremy
jeremy

Reputation: 10057

This should do it.

var date = new Date(Date.parse("2012-12-20 21:34:09"));
var converted = date.getDate() + "/" + (date.getMonth()+1) + "/" + date.getFullYear();

It's worthwhile to note that this will only work in Chrome and Opera. (Thanks to Gaby aka G. Pertrioli)

Upvotes: 1

Andreas Hagen
Andreas Hagen

Reputation: 2325

You could parse the date and the reprint it. Something like this:

var date = new Date( Date.parse( "2012-12-20 21:34:09" ) );
var formattedDate = date.getDate() + "/" + ( date.getMonth() + 1 ) + "/" + date.getFullYear();

Upvotes: 0

Gabriele Petrioli
Gabriele Petrioli

Reputation: 195972

You could try

var mydate = '2012-12-20 21:34:09';
var formatteddate = mydate.split(' ')[0].split('-').reverse().join('/');

Upvotes: 1

Related Questions