Reputation: 59
How to convert Convert May 13, 2012 12:00:00 AM to 13/05/2012 using javascript.
Upvotes: 1
Views: 41
Reputation: 1279
I think you could consider use a library to do that convert instead of convert it yourself.
moment.js is a great lib to do such thing. You just need oneline.
moment('May 13, 2012 12:00:00').format('DD/MM/YYYY')
You only need change the format string if you need use another format without change other code.
Upvotes: 0
Reputation: 147473
It is generally recommended to not parse date strings, even those mentioned in ECMA-262 due to browser inconsistencies. You can use a library, but the format in the OP is not difficult:
function parseMMMDY(s) {
var b = s.toLowerCase().match(/\w+/g);
var months = {jan:'01',feb:'02',mar:'03',apr:'04',may:'05',jun:'06',
jul:'07',aug:'08',sep:'09',oct:'10',nov:'11',dec:'12'};
return b && b[1] + '/' + months[b[0]] + '/' + b[2];
}
var s = 'May 13, 2012 12:00:00 AM'
document.write(parseMMMDY(s)); // 13/05/2012
If you need a Date object and parsing of the time component is also required, that isn't difficult either.
Upvotes: 0
Reputation: 25352
Try like this
var d = new Date("May 13, 2012 12:00:00 AM");
var curr_date = d.getDate();
var curr_month = d.getMonth() + 1; //Months are zero based
var curr_year = d.getFullYear();
var formatedDate=(curr_date<10 ? "0"+curr_date:curr_date) + "/" + (curr_month<10? "0"+curr_month:curr_month ) + "/" + curr_year;
console.log(formatedDate);
Upvotes: 1