假设我有一个特定的日期,例如:21-03-2013
,我希望得到我使用的月份:moment("04-03-2013","DD-MM-YYYY").format('MMMM');
这给了我三月。
现在是今天的日期,我使用了moment().format('MM');
给了我十月。
我如何获得名字之间的所有月份?
答案 0 :(得分:2)
这也适用于更长的时间段(> 1年) - 如有必要
function getDates(startDate /*moment.js date object*/) {
nowNormalized = moment().startOf("month"), /* the first of current month */
startDateNormalized = startDate.clone().startOf("month").add("M", 1), /* the first of startDate + 1 Month - as it was asked for the months in between startDate and now */
months = [];
/* .isBefore() as it was asked for the months in between startDate and now */
while (startDateNormalized.isBefore(nowNormalized)) {
months.push(startDateNormalized.format("MMMM"));
startDateNormalized.add("M", 1);
}
return months;
}
<强>更新强>
正如Matt在评论中所建议的那样,我现在使用.clone()
和.startOf("month")
而不是自己创建规范化克隆
答案 1 :(得分:1)
此函数采用格式为“DD-MM-YYYY”的字符串,并返回一个数组,其中包含从该日期起的所有月份到当前
function getMonths(startDate){
var startMonth = parseInt(startDate.split('-')[1], 10),
endMonth = parseInt(moment().format('M'), 10),
monthArray = [];
if( startMonth < 1 ) return [];
for( var i = startMonth; i != endMonth; i++ ){
if( i > 12 ) i = 1;
monthArray.push( moment(i, "M").format("MMMM") );
}
monthArray.push(moment().format('MMMM'));
return monthArray;
}
getMonths("04-03-2013");