22

How can i make it nicer?

var month = new Array();

month['01']='Jan';
month['02']='Feb';
month['03']='Mar';

etc. Itd be nice to do it like:

var months = new Array(['01','Jan'],['02','Feb'],['03','Mar']);

For example. anyway like that to simplify it?

3
  • To be clear you are creating an object not an array. You are actually defining the properties of month. For this reason you will not get what your expecting if you alert(month.length); Commented Jul 16, 2010 at 0:14
  • Sorry, i should have said, im creating a new array object... Commented Jul 16, 2010 at 17:19
  • 2
    Am I the only who came here just to copy-paste the month array from answers? ( because I am too lazy to write on my own ) Commented Jul 29, 2017 at 6:43

9 Answers 9

42

For a more natural approach, try this little snippet. It works with Date objects and just as a regular function:

'use strict';

(function(d){
    var mL = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
    var mS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'June', 'July', 'Aug', 'Sept', 'Oct', 'Nov', 'Dec'];

    d.prototype.getLongMonth = d.getLongMonth = function getLongMonth (inMonth) {
        return gM.call(this, inMonth, mL);
    }

    d.prototype.getShortMonth = d.getShortMonth = function getShortMonth (inMonth) {
        return gM.call(this, inMonth, mS);
    }

    function gM(inMonth, arr){
        var m;

        if(this instanceof d){
            m = this.getMonth();
        }
        else if(typeof inMonth !== 'undefined') {
            m = parseInt(inMonth,10) - 1; // Subtract 1 to start January at zero
        }

        return arr[m];
    }
})(Date);

You can directly copy and paste this, then use it like this:

var today = new Date();
console.log(today.getLongMonth());
console.log(Date.getLongMonth(9));          // September
console.log(today.getShortMonth());
console.log(Date.getShortMonth('09'));      // Sept

This technique will provide flexibility as to how you index and how you access it. When using the Date object it will work correctly, but if using it as a standalone function it considers the months in human readable format from 1-12.

Fiddle with it!

Sign up to request clarification or add additional context in comments.

2 Comments

This serves as a great base for further development. And thanks for the fiddle!
I knew I had to do this, and I was like, "Man, I don't want to have to type in all those names into an array! I bet one of our SO buddies has already done it." - and POW - I had a copy/paste in 15 seconds! LOL thanks for enabling my laziness :)
24

this should do it ..

var months = {'01':'Jan', '02':'Feb'};
alert( months['01'] );

3 Comments

damn it, duh, JSON... Thanks!
Oh, and ill update you as the right answer after I wait the 10 mins it says I have to wait...
Keep in mind that if you plan on using the Date object that months begin with 0 (i.e. Jan = 0, Feb =1)
19

Short Dynamic Solution:

Here's a dynamic solution that does not require hard-coding an array of months:

const month = f=>Array.from(Array(12),(e,i)=>new Date(25e8*++i).toLocaleString('en-US',{month:f}));

Test Cases:

// Using Number Index:

month`long`[0];    // January
month`long`[1];    // February
month`long`[2];    // March

month`short`[0];   // Jan
month`short`[1];   // Feb
month`short`[2];   // Mar

month`narrow`[0];  // J
month`narrow`[1];  // F
month`narrow`[2];  // M

month`numeric`[0]; // 1
month`numeric`[1]; // 2
month`numeric`[2]; // 3

month`2-digit`[0]; // 01
month`2-digit`[1]; // 02
month`2-digit`[2]; // 03

// Using String Index:

let index_string = '01';

month`long`[index_string-1];    // January
month`short`[index_string-1];   // Jan
month`narrow`[index_string-1];  // J
month`numeric`[index_string-1]; // 1
month`2-digit`[index_string-1]; // 01

Comments

7

why not:

var month = [
  'Jan', 
  'Feb', 
  // ...
  'Dec'];

To get the month name from the number you'd do something like:

var monthNum = 2; // February
var monthShortName = month[monthNum-1];

5 Comments

Imagine that, using numerical indices on an array object. Whatever next!?
Object indexes Andy, comon. var one = {'1': 'one'}; var month = {}; month[one] = "Jan";
Hahah Anurag I think I'm going to be sick
@Andy E - dude what happened to your head?!
@bears: horrific bear accident. If only I'd seen your screen name beforehand. Fortunately my head was intact - my body was just holding me back anyway ;-)
2

Here is very simple approach to get month name :

<script>
function getMonth(month){
    month = month-1;
    var months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];

    if(months[month] != null){
        return months[month];
    }else{
        throw "Invalid Month No";
    }
}

try{
    monthName = getMonth(8);
    alert("Month Is : " + monthName);
}catch(e){
    console.log(e);
}
</script> 

Comments

1

Don't use an Array unless you're using real numeric indexes. Try this:

var month = {
    '01': 'Jan',
    '02': 'Feb',
    // ...
    '12': 'Dec'
};

Personally, though, I would wrap this kind of logic in a function:

var monthNames = ['Jan', 'Feb', /* ... */ 'Dec'];
function getMonthName(n) {
    return monthNames(n - 1);
}

alert(getMonthName(1)); // 'Jan'

That way, you never have to think about the underlying data structure, or worry about changing it later.

Comments

0

You can use nice library https://github.com/pret-a-porter/month-list

  • getMonthList('en', 'short') for short names ["Jan", "Feb", ...]
  • getMonthList('en', '2-digit') for numeric strings ["01", "02", ...]

Comments

-1

Months in javascript for faster access O(1)

const months = { "01": "Jan", "02": "Feb", "03": "Mar", "04": "Apr", "05": "May", "06": "Jun", "07": "Jul", "08": "Aug", "09": "Sep", "10": "Oct",

"11": "Nov",

"12": "Dec", };

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
-2
import java.util.*;

public class NumOfMonth
{
  public static void main(String args[]) {

    Scanner in = new Scanner (System.in);

    String months[] = {"","Jan", "Feb", "March", "april" , "june", "july", "august", "sept", "oct", "nov","Dec`1"};
    int m = 0;
    System.out.format("enter the number of month:");
    m = in.nextInt();
    System.out.println(months[m]);
  }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.