Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get month from string in javascript?

I have tried

     var d=new Date("2012-07-01 00:00:00.0");
     alert(d.getMonth());   

But getting NAN.

I want month as July for the above date.

like image 745
Edward Avatar asked Sep 03 '12 10:09

Edward


People also ask

How can I get my current month name?

JavaScript Date getMonth() getMonth() returns the month (0 to 11) of a date.

What value is returned by Get month in April in JavaScript?

Javascript date getMonth() method returns the month in the specified date according to local time. The value returned by getMonth() is an integer between 0 and 11.

What does the getMonth () method of the date object return?

The getMonth() method returns the month in the specified date according to local time, as a zero-based value (where zero indicates the first month of the year).


1 Answers

Try this:

    var monthNames = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"]
    var str="2012-07-01";   //Set the string in the proper format(best to use ISO format ie YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS)
    var d=new Date(str);  //converts the string into date object
    var m=d.getMonth(); //get the value of month
    console.log(monthNames[m]) // Print the month name

NOTE: The getMonth() returns the value in range 0-11.

Another option is to use toLocaleString

var dateObj = new Date("2012-07-01");
//To get the long name for month
var monthName = dateObj.toLocaleString("default", { month: "long" }); 
// monthName = "November"

//To get the short name for month
var monthName = dateObj.toLocaleString("default", { month: "short" });
// monthName = "Nov"
like image 185
heretolearn Avatar answered Oct 10 '22 11:10

heretolearn