Tuesday, May 15, 2012

Get Month Name In Javascript

Month Name in JavaScript.
Get Month Name Javascript.
Javascript Date Object, Months Names.

There's a very simple way to get the month's name in javascript.  The only problem is, that people do it over and over instead of just placing this in the Date object.

Do, the solution is rather simple:

     Date.prototype.getMonthName = function() {
          var monthNames = [ "January""February""March""April""May""June", 
                        "July""August""September""October""November""December" ];
          return monthNames[this.getMonth()];
     }

Next time you'll want to get a name you can just:
      var month_Name = new Date().getMonthName();

p.s.
Sometime in the near future I'll upload a file with all of my extensions to Javascript's Array and Date objects.

Elad Shalom,
CTO at ITweetLive.com

10 comments:

  1. You can leave out the var and just return [...][this.getMonth()

    ReplyDelete
  2. You can, but in case of JS Error you'll get hard times finding the exact error. Plus, when you learn new things, you'd better put everything as simple as possible. Worry about optimization later :)

    ReplyDelete
  3. var d= new date(); alert(d.getMonth);
    This script is giving me wrong month for instance if today is month 9(September) but this script giving me 8(august) so in result I am receiving wrong month. please tell me what should I do?

    ReplyDelete
    Replies
    1. 0 is for january, then, 8 is for september

      Delete