Reputation: 223
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
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
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
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
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
Reputation: 195972
You could try
var mydate = '2012-12-20 21:34:09';
var formatteddate = mydate.split(' ')[0].split('-').reverse().join('/');
Upvotes: 1