如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?

var objDate = new Date("10/11/2009");

当前回答

现在的自然格式是使用Moment.js。

在Moment.js中,以字符串格式获取月份的方法非常简单,不需要在代码中硬编码月份名称: 要获得当前月份和年份的月份名称格式和全年(2015年5月):

  moment(new Date).format("MMMM YYYY");

其他回答

对于momentjs,只需使用格式符号。

const myDate = new Date()
const shortMonthName = moment(myDate).format('MMM') // Aug
const fullMonthName = moment(myDate).format('MMMM') // August

您可以使用几种可用的日期格式化程序之一。因为这属于JavaScript规范,所以它可以在浏览器和服务器端模式下使用。

objDate.toString().split(" ")[1]; // gives short name, unsure about locale 
objDate.toLocaleDateString.split(" ")[0]; // gives long name

e.g.

js> objDate = new Date(new Date() - 9876543210)
Mon Feb 04 2013 12:37:09 GMT-0800 (PST)
js> objDate.toString().split(" ")[1]
Feb
js> objDate.toLocaleString().split(" ")[0]
February

更多信息请访问https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date

如果你使用剑道,也可以这样做。

kendo.toString(dateobject, "MMMM");

以下是kendo网站上的格式化器列表:

"d" Renders the day of the month, from 1 through 31. "dd" The day of the month, from 01 through 31. "ddd" The abbreviated name of the day of the week. "dddd" The full name of the day of the week. "f" The tenths of a second in a date and time value. "ff" The hundredths of a second in a date and time value. "fff" The milliseconds in a date and time value. "M" The month, from 1 through 12. "MM" The month, from 01 through 12. "MMM" The abbreviated name of the month. "MMMM" The full name of the month. "h" The hour, using a 12-hour clock from 1 to 12. "hh" The hour, using a 12-hour clock from 01 to 12. "H" The hour, using a 24-hour clock from 1 to 23. "HH" The hour, using a 24-hour clock from 01 to 23. "m" The minute, from 0 through 59. "mm" The minute, from 00 through 59. "s" The second, from 0 through 59. "ss" The second, from 00 through 59. "tt" The AM/PM designator. "yy" The last two characters from the year value. "yyyy" The year full value. "zzz" The local timezone when using formats to parse UTC date strings.

现在可以使用ECMAScript国际化API来做到这一点:

const date = new date (2009,10,10);/ / 2009-11-10 Const month =日期。toLocaleString('default', {month: 'long'}); console.log(月);

“long”使用月份的全称,“short”使用简短的名称,“narrow”使用更简洁的版本,比如字母语言中的第一个字母。

你可以将浏览器的“默认”更改为任何你喜欢的语言环境(例如:'en-us'),它将为该语言/国家使用正确的名称。

使用toLocaleStringapi,你每次都必须传递locale和选项。如果你要在多个不同的日期使用相同的语言环境信息和格式选项,你可以使用Intl。DateTimeFormat相反:

const formatter = new Intl。DateTimeFormat('fr', {month: 'short'}); Const month1 =格式化程序。格式(新日期()); Const month2 = formatter。format(new Date(2003,5,12)); Console.log (' ${month1}和${month2} ');//当前月份的法语和“juin”。

有关更多信息,请参阅我关于国际化API的博客文章。

如果你正在使用jQuery,你可能也在使用jQuery UI,这意味着你可以使用$.datepicker. formatdate()。

$.datepicker.setDefaults( $.datepicker.regional[ "nl" ] );   // dutch
$.datepicker.formatDate( "dd MM yy", objDate );