如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
如何在JavaScript中从这个日期对象生成月份的名称(例如:10月/ 10月)?
var objDate = new Date("10/11/2009");
当前回答
不幸的是,提取月份名称的最佳方法是从UTCString表示中提取:
Date.prototype.monthName = function() {
return this.toUTCString().split(' ')[2]
};
d = new Date();
//=> Thu Mar 06 2014 23:05:21 GMT+0000 (GMT)
d.monthName();
//=> 'Mar'
其他回答
我是通过DatePipe完成的。
const datePipe = new DatePipe(this.locale);
datePipe.transform(myDate, 'MMM. y');
你可以像这样在构造函数中注入默认区域:
constructor(@Inject(LOCALE_ID) private locale: string){}
Angular的引用https://angular.io/api/common/DatePipe
将名称存储在一个数组中,并根据月份的索引进行查找。
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()方法
你可以使用或不使用当地语言翻译
创造价值“2009年10月11日”
const objDate =新日期("10/11/2009"); const月=[‘简’,2月,3月,4月,“可能”,“君”,7月,8月,9月,10月,11月,12月的) if (objDate !== '无效日期' && !isNaN(objDate)) { console.log(objDate.getDate() + ' ' + months[objDate.getMonth()] + ' ' + objDate.getFullYear())) }
ECMAScript国际化API将month转换为本地语言(例如:october 11)
const convertDate = new Date('10/11/2009') Const lang = 'fr' // de, es, ch if (convertDate !== '无效日期' && !isNaN(convertDate)) { console.log(convertDate. getdate () + ' ' + convertDate. log)toLocaleString(朗,{ 月:“长” })) }
这里是一个函数,你将1传递给12,并返回完整的月份名称例如" January "或" July "
function getMonthName(monthNumber) {
return new Date('1999-' + monthNumber + '-15').toLocaleString('en-us', { month: 'long' })
}
如果我们需要传递输入,那么我们需要使用以下方式
输入:“2020-12-28”
代码:
new Date('2020-12-28').toLocaleString('en-us',{month:'short', year:'numeric'})
输出:“2020年12月”