How to get a date format from date string value? [duplicate]

I need to parse the date in javascript for 17Dec2010 as javascript date. How to do that?


Solution 1:

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

Solution 2:

Using Crowder's regExp instead of the one I came up with when I first answered, there is no need for a month array. My script was tested in IE8, Fx 3.6, Opera 10, Safari 5, Mozilla 1.7 on windows and Blackberry native browser. If the month part of your string is English, then all major browsers and even some not so major ones - I expect all browsers with javascript support and Date.parse support will handle my script just fine. MDC says Date.parse does RFC822

<script type="text/javascript">
var date = "12Dec2011"
var reg = /^(\d+)(\D+)(\d+)$/
var parts = reg.exec(date)
var dateString = parts[1]+' '+parts[2]+' '+parts[3]; // parts[0] is the match itself
alert(new Date(Date.parse(dateString)))
</script>