如何从javascript中的字符串获取月份?

Edw*_*ard 5 javascript date

我试过了

     var d=new Date("2012-07-01 00:00:00.0");
     alert(d.getMonth());   
Run Code Online (Sandbox Code Playgroud)

但是得到NAN.

我想要上个月的月份July.

Cly*_*obo 15

假设您的日期是YYYY-MM-DD格式

var arr = "2012-07-01 00:00:00.0".split("-");
var months = [ "January", "February", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December" ];
var month_index =  parseInt(arr[1],10) - 1;
console.log("The current month is " + months[month_index]);
Run Code Online (Sandbox Code Playgroud)


dan*_*xon 7

使用JavaScript国际化API:

var date = new Date("2012-07-01");

var monthName = new Intl.DateTimeFormat("en-US", { month: "long" }).format;
var longName = monthName(date); // "July"

var shortMonthName = new Intl.DateTimeFormat("en-US", { month: "short" }).format;
var shortName = shortMonthName(date); // "Jul"
Run Code Online (Sandbox Code Playgroud)

  • 似乎每个现代浏览器都支持 http://caniuse.com/#search=internationalization (2认同)

her*_*arn 6

尝试这个:

    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
Run Code Online (Sandbox Code Playgroud)

注意: getMonth() 返回 0-11 范围内的值。

另一种选择是使用 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"
Run Code Online (Sandbox Code Playgroud)