0

I Have seen quite a lot of solutions for getting the month name of a Date object in JavaScript, mostly using an array or object of month names and matching them to the value of Date.getMonth() or Date.getUTCMonth().

Here is one of the more popular examples.

Whilst this approach works fine, I am wondering if I can get the name straight from the date object itself. We already have various versions of 'toString' which all provide a month name as part of their return string.

<!DOCTYPE html>
<html>
<body>
    <div id="tostring"></div>
    <div id="todatestring"></div>
    <div id="toutcdatestring"></div>
    <script>
        var a = new Date();
        document.getElementById("tostring").innerHTML = a.toString();
        document.getElementById("todatestring").innerHTML = a.toDateString();
        document.getElementById("toutcdatestring").innerHTML = a.toUTCString();
    </script>
</body>
</html>

So why cant we get the month name straight from a date object, or at least get access to what ever mechanism date has for mapping names to months?

Community
  • 1
  • 1
Jeremy
  • 3,418
  • 2
  • 32
  • 42
  • 1
    Heh, I get the feeling that if this was possible, all of the examples you've come across would have used it, rather then defining their own arrays ;). – Matt May 23 '13 at 22:23
  • 1
    The trivial answer for why you can't "get the month name straight from a date object" because ECMA-262 doesn't include a "getMonthAsString" method, but you can easily add one. Note that you will need to take account of different language settings. – RobG May 23 '13 at 23:21

1 Answers1

0

The month names you get from .toUTCString() are 3-letter names, so: Jan, Feb, Apr etc.

I think that's the best you can do. Having a list of month names isn't so odd. It's not too inconvenient, month names don't change all that often after all ;)

Halcyon
  • 57,230
  • 10
  • 89
  • 128
  • 2
    The value returned by [*toUTCString*](http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.5.42) is implementation dependent and does not necessarily contain a month name. The [recommended format](http://www.ecma-international.org/ecma-262/5.1/#sec-15.9.1.15) is a version of ISO8601 and does not use month names. – RobG May 23 '13 at 23:05