Month Array in JavaScript Not Pretty
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)); // Septemberconsole.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.
this should do it ..
var months = {'01':'Jan', '02':'Feb'};alert( months['01'] );
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]; // Januarymonth`long`[1]; // Februarymonth`long`[2]; // Marchmonth`short`[0]; // Janmonth`short`[1]; // Febmonth`short`[2]; // Marmonth`narrow`[0]; // Jmonth`narrow`[1]; // Fmonth`narrow`[2]; // Mmonth`numeric`[0]; // 1month`numeric`[1]; // 2month`numeric`[2]; // 3month`2-digit`[0]; // 01month`2-digit`[1]; // 02month`2-digit`[2]; // 03// Using String Index:let index_string = '01';month`long`[index_string-1]; // Januarymonth`short`[index_string-1]; // Janmonth`narrow`[index_string-1]; // Jmonth`numeric`[index_string-1]; // 1month`2-digit`[index_string-1]; // 01