如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
当前回答
您可以使用datejs来实现这一点。检查格式说明符,MMMM给出了月份的名称:
var objDate = new Date("10/11/2009");
document.write(objDate.toString("MMMM"));
datejs本地化了超过150个locale !在这里看到的
其他回答
如果你不想使用一个外部库,或者存储一个月份名称的数组,或者如果ECMAScript国际化API因为浏览器兼容性而不够好,你可以通过从日期输出中提取信息来实现:
var now = new Date();
var monthAbbrvName = now.toDateString().substring(4, 7);
这将为您提供缩写的月份名称,例如october。我相信日期将以各种格式出现,这取决于初始化和您的地区,因此请查看toDateString()返回的内容,并基于此重新计算您的substring()值。
最简单最简单的方法:
const dateStr =新的日期(2020,03,10).toDateString();//“2020年4月10日星期五” const dateStrArr = dateStr。分割(' ');// ['Fri', 'Apr', '10', '2020'] console.log (dateStrArr [1]);/ / 4月的
将日期转换为字符串。 间隔一个空格。 从数组中选择第二个元素。
将名称存储在一个数组中,并根据月份的索引进行查找。
var month=new Array(12);
month[0]="January";
month[1]="February";
month[2]="March";
month[3]="April";
month[4]="May";
month[5]="June";
month[6]="July";
month[7]="August";
month[8]="September";
month[9]="October";
month[10]="November";
month[11]="December";
document.write("The current month is " + month[d.getMonth()]);
JavaScript getMonth()方法
只需要编写一个简单的toLocaleString包装器:
函数 LocalDate(locale) { this.locale = locale; } LocalDate.prototype.getMonthName = function(date) { return date.toLocaleString(this.locale,{month:“long”}); }; var objDate = new Date(“10/11/2009”); var localDate = new LocalDate(“en”); console.log(localDate.getMonthName(objDate)); localdate.locale = “ru”; console.log(localDate.getMonthName(objDate)); localdate.locale = “zh”; console.log(localDate.getMonthName(objDate));
只是扩展了许多其他优秀的答案-如果你正在使用jQuery -你可以做一些类似的事情
$.fn.getMonthName = function(date) {
var monthNames = [
"January", "February", "March",
"April", "May", "June",
"July", "August", "September",
"October", "November", "December"
];
return monthNames[date.getMonth()];
};
其中date等于var d = new date (somevalue)。这样做的主要优点是@nickf避免使用全局名称空间。