Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easiest way to convert month name to month number in JS ? (Jan = 01)

Just want to covert Jan to 01 (date format)

I can use array() but looking for another way...

Any suggestion?

like image 626
l2aelba Avatar asked Nov 26 '12 14:11

l2aelba


People also ask

How do I convert month number to month name in react?

This below function takes the month number (like 1 or 2) as an argument and returns the month name in string format. Let's learn how the above function works: First we initialized a JavaScript new Date() constructor. We invoked a setMonth() method on JavaScript date Object by passing the month-1 as an argument.

How do you convert month numbers to months?

Please do as follows: Select a blank cell next to the sales table, type the formula =TEXT(A2*29,"mmm") (Note: A2 is the first number of the Month list you will convert to month name), and then drag the AutoFill Handle down to other cells. Now you will see the numbers (from 1 to 12) are converted to normal month names.

How do you convert a string to a number in JavaScript?

How to convert a string to a number in JavaScript using the parseInt() function. Another way to convert a string into a number is to use the parseInt() function. This function takes in a string and an optional radix. A radix is a number between 2 and 36 which represents the base in a numeral system.


1 Answers

Just for fun I did this:

function getMonthFromString(mon){    return new Date(Date.parse(mon +" 1, 2012")).getMonth()+1 } 

Bonus: it also supports full month names :-D Or the new improved version that simply returns -1 - change it to throw the exception if you want (instead of returning -1):

function getMonthFromString(mon){     var d = Date.parse(mon + "1, 2012");    if(!isNaN(d)){       return new Date(d).getMonth() + 1;    }    return -1;  } 

Sry for all the edits - getting ahead of myself

like image 154
Aaron Romine Avatar answered Sep 27 '22 20:09

Aaron Romine