0

How do you convert a date or a string with this format '10-Aug-13' into 'mm-dd-yyyy' using javascript?

 var date =  new Date('10-Aug-13');

The code above returns Invalid date using IE10, but works well on other browsers.

abc
  • 157
  • 3
  • 14

6 Answers6

2

Can you use an external library? If yes, I'd recommend this one http://www.datejs.com/ , then you'd do something like this:

var date = Date.parse('10-Aug-13'); // works on IE8+, Chrome, Firefox, Opera
Nicolae Olariu
  • 2,487
  • 2
  • 18
  • 30
1

I'm going to assume that the year will always be for the current century, which you can add as follows:

var currentYear, parts;

currentYear = new Date().getFullYear().toString();
parts = "10-Aug-13".split("-");
parts[2] = currentYear.substring(0, currentYear.length - 2) + parts[2];

var date = new Date(parts.join(" "));

However if you don't care about the century you can just default it to 1, like so:

var parts, date;
parts = "10-Aug-99".split("-");
parts[2] = "1" + parts[2];
date = new Date(parts.join(" "))

Also I've also removed the "-" from the date string as FF didn't seem to like that.

Castrohenge
  • 8,525
  • 5
  • 39
  • 66
1

hope this js function below helps, the date parameter should always in 'DD-MMM-YY' format

function formatDate(dateparam) {
    var m_array = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
                   "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
    var dtparts = dateparam.split('-');
    var dateObj = new Date("20" + dtparts[2], m_array.indexOf(dtparts [1]), dtparts[0]);

    var date = dateObj.getDate();
    date = (date.toString().length == 1) ? "0" + date : date;
    var month = dateObj.getMonth() + 1;
    month = (month.toString().length == 1) ? "0" + month : month;
    var year = dateObj.getFullYear();

    return month + "-" + date + "-" + year;
}
document.write(formatDate("10-Aug-13"));
icaru12
  • 1,522
  • 16
  • 21
0

Try this one...

date.format("mm-dd-yyyy");
Ganesh Rengarajan
  • 2,006
  • 13
  • 26
0
var date=new Date('10-Aug-13');
console.log((date.getMonth()+1)+'/'+date.getDate())+'/'+date.getFullYear()+);

OR

var d = new Date();
d.setMonth(8,10);
d.setFullYear(2013);
d.toString('MM-dd-yyyy');
Prince Kumar Sharma
  • 12,591
  • 4
  • 59
  • 90
0
var date=new Date('10-Aug-13');
date = (date.getMonth()+1)+'/'+date.getDate())+'/'+date.getFullYear();
Lonely
  • 613
  • 3
  • 6
  • 14