如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
当前回答
您可以使用几种可用的日期格式化程序之一。因为这属于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
其他回答
文档。写(新日期()。toLocaleString('en-us',{月:'长',年:'数字',日:'数字'}))
我衷心推荐moment.js库中的format函数,你可以这样使用它:
moment().format("MMM"); // "Apr" - current date
moment(new Date(2012, 01, 04)).format("MMM"); // "Feb" - from a local date
moment.utc(new Date(2012, 00, 04).format("MMM"); // "Jan" - from a UTC date
如果你需要当月的全称,可以用“MMMM”而不是“MMM”
除了一长串其他特性之外,它还具有强大的国际化支持。
如果你不想使用一个外部库,或者存储一个月份名称的数组,或者如果ECMAScript国际化API因为浏览器兼容性而不够好,你可以通过从日期输出中提取信息来实现:
var now = new Date();
var monthAbbrvName = now.toDateString().substring(4, 7);
这将为您提供缩写的月份名称,例如october。我相信日期将以各种格式出现,这取决于初始化和您的地区,因此请查看toDateString()返回的内容,并基于此重新计算您的substring()值。
如果你使用剑道,也可以这样做。
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.
如果您不介意扩展Date原型(并且有一些很好的理由不想这样做),您实际上可以提出一个非常简单的方法:
Date.prototype.monthNames = [
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
];
Date.prototype.getMonthName = function() {
return this.monthNames[this.getMonth()];
};
Date.prototype.getShortMonthName = function () {
return this.getMonthName().substr(0, 3);
};
// usage:
var d = new Date();
alert(d.getMonthName()); // "October"
alert(d.getShortMonthName()); // "Oct"
这些函数将应用于所有javascript Date对象。