Last active
November 21, 2022 03:19
-
-
Save richard512/2c8e6ad2469033e006f1 to your computer and use it in GitHub Desktop.
JavaScript: Month name to Number and Month number to month name
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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!') |
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.
If you plan to use this with js Date function you will want the 'Jan' date to be 0.
and then Feb 2 ???
`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
This has a bug. If you pass in January, you get 0 back instead of 1..
Should be
return month != -1 ? month + 1 : undefined