Skip to content

Instantly share code, notes, and snippets.

@richard512
Last active November 21, 2022 03:19
Show Gist options
  • Save richard512/2c8e6ad2469033e006f1 to your computer and use it in GitHub Desktop.
Save richard512/2c8e6ad2469033e006f1 to your computer and use it in GitHub Desktop.
JavaScript: Month name to Number and Month number to month name
var months = [
'January', 'February', 'March', 'April', 'May',
'June', 'July', 'August', 'September',
'October', 'November', 'December'
];
function monthNumToName(monthnum) {
return months[monthnum - 1] || '';
}
function monthNameToNum(monthname) {
var month = months.indexOf(monthname);
return month ? month + 1 : 0;
}
if (monthNumToName(12) == 'December') alert('12 == December!')
if (monthNameToNum('June') == 6) alert('June == 6!')
@shanness
Copy link

shanness commented Jan 8, 2019

This has a bug. If you pass in January, you get 0 back instead of 1..
Should be
return month != -1 ? month + 1 : undefined

@racouster
Copy link

This has a bug. If you pass in January, you get 0 back instead of 1..
Should be
return month != -1 ? month + 1 : undefined

If you plan to use this with js Date function you will want the 'Jan' date to be 0.

@naftalib
Copy link

If you plan to use this with js Date function you will want the 'Jan' date to be 0.

and then Feb 2 ???

@iamhasibulhasan
Copy link

`const moment = require('moment');
moment.locale('en'); // sets words language (optional if current locale is to be used)
let months = moment.months() // returns a list of months in the current locale (January, February, etc.)
// console.log(months);
var months_obj = {};

for (let month_num_key in months) {
months_obj[parseInt(month_num_key) + 1] = months[month_num_key];
}

console.log(months_obj);`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment