如何在 JavaScript 中从这个日期对象生成月份的名称(例如:十月/十月)?
var objDate = new Date("10/11/2009");
较短的版本:
const monthNames = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"
];
const d = new Date();
document.write("The current month is " + monthNames[d.getMonth()]);
注意 (2019-03-08) – 我最初在 2009 年写的这个答案已经过时了。请参阅David Storey的答案以获得更好的解决方案。
现在可以使用 ECMAScript 国际化 API 来做到这一点:
const date = new Date(2009, 10, 10); // 2009-11-10
const month = date.toLocaleString('default', { month: 'long' });
console.log(month);
'long'
使用月份的全名作为短名称,以及更小的版本,例如按字母顺序排列的第一个字母。'short'
'narrow'
您可以将语言环境从浏览器更改为您喜欢的任何语言(例如),它将使用该语言/国家/地区的正确名称。'default'
'en-us'
使用 api,您每次都必须传入区域设置和选项。如果您要在多个不同的日期使用相同的区域设置信息和格式选项,则可以改用:toLocaleString
Intl.DateTimeFormat
const formatter = new Intl.DateTimeFormat('fr', { month: 'short' });
const month1 = formatter.format(new Date());
const month2 = formatter.format(new Date(2003, 5, 12));
console.log(`${month1} and ${month2}`); // current month in French and "juin".
有关更多信息,请参阅我关于国际化 API 的博客文章。
这是另一个,支持本地化 🙂
Date.prototype.getMonthName = function(lang) {
lang = lang && (lang in Date.locale) ? lang : 'en';
return Date.locale[lang].month_names[this.getMonth()];
};
Date.prototype.getMonthNameShort = function(lang) {
lang = lang && (lang in Date.locale) ? lang : 'en';
return Date.locale[lang].month_names_short[this.getMonth()];
};
Date.locale = {
en: {
month_names: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
month_names_short: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
}
};
然后,您可以轻松添加对其他语言的支持:
Date.locale.fr = {month_names: [...]};
模板简介:该模板名称为【JavaScript 从日期获取月份名称】,大小是暂无信息,文档格式为.编程语言,推荐使用Sublime/Dreamweaver/HBuilder打开,作品中的图片,文字等数据均可修改,图片请在作品中选中图片替换即可,文字修改直接点击文字修改即可,您也可以新增或修改作品中的内容,该模板来自用户分享,如有侵权行为请联系网站客服处理。欢迎来懒人模板【JavaScript】栏目查找您需要的精美模板。