The short answer is: There’s no standard means in JavaScript for doing that, you’ll have to do it yourself. JavaScript only recently got any standard string representation for dates (as of ECMAScript 5th edition, about a year ago — the format is a simplified version of ISO-8601), and your format doesn’t match that format.
However, there are add-on libraries that can help, such as DateJS.
Your particular format is pretty easy to parse (see below), but if you get into variations, it can get complex fast.
Simple example:
var months = {
en: {
"jan": 0,
"feb": 1,
"mar": 2,
"apr": 3,
"may": 4,
"jun": 5,
"jul": 6,
"aug": 7,
"sep": 8,
"oct": 9,
"nov": 10,
"dec": 11
}
};
var dateString = "17Dec2010";
var dt = new Date(
parseInt(dateString.substring(5), 10), // year
months.en[dateString.substring(2, 5).toLowerCase()], // month
parseInt(dateString.substring(0, 2), 10) // day
);
alert(dt); // alerts "Fri Dec 17 2010 00:00:00 GMT+0000 (GMT)" or similar
Live example
…but that only handles English (hence the en
property of months
) and again, it can get complex fairly quickly.
mplungjan quite correctly points out that the above will fail on, say “7Dec2010”. Here’s a version that’s a bit more flexible, but again, I’d probably look to a library if there’s any variety in the format:
var months = {
en: {
"jan": 0,
"feb": 1,
"mar": 2,
"apr": 3,
"may": 4,
"jun": 5,
"jul": 6,
"aug": 7,
"sep": 8,
"oct": 9,
"nov": 10,
"dec": 11
}
};
var dateString = "17Dec2010";
var parts = /^(\d+)(\D+)(\d+)$/.exec(dateString);
if (parts && parts.length == 4) {
var dt = new Date(
parseInt(parts[3], 10), // year
months.en[parts[2].toLowerCase()], // month
parseInt(parts[1], 10) // day
);
display(dt);
}
else {
display("Date '" + dateString + "' not recognized");
}
Live example