根据日期范围,我尝试创建四个字符串列表,其中包含以特定方式格式化的周,月,季度和年份。
以下代码工作正常(请注意计算周数的特殊方法。这是预期的。)
我的问题是,一旦dateEnd被定义为在下一年(例如03-28-2019),实施就会失败。然后,生成的列表变得不完整/不正确。
有没有更好的方法来实现目标?
这是一个小提琴... https://jsbin.com/wipehahigo/1/edit?html,js,console
_id
更新和解决方案
我现在这样做...... https://jsbin.com/mepifevico/1/edit?html,js,console
dateStart = "01-01-2018";
dateEnd = "03-28-2018";
//get list of week strings
lowerRange = Math.ceil(moment(dateStart, "MM-DD-YYYY").dayOfYear()/7);
upperRange = Math.ceil(moment(dateEnd, "MM-DD-YYYY").dayOfYear()/7);
year = moment(dateStart, "MM-DD-YYYY").year();
weekList = []
for (var i = lowerRange; i <= upperRange; i++) {
weekList.push('W' + i + '_' + year);
}
//get list of month strings
lowerRange = moment(dateStart, "MM-DD-YYYY").month()+1;
upperRange = moment(dateEnd, "MM-DD-YYYY").month()+1;
year = moment(dateStart, "MM-DD-YYYY").year();
monthList = []
for (var i = lowerRange; i <= upperRange; i++) {
monthList.push('M' + i + '_' + year);
}
//get list of quarter strings
lowerRange = moment(dateStart, "MM-DD-YYYY").quarter();
upperRange = moment(dateEnd, "MM-DD-YYYY").quarter();
year = moment(dateStart, "MM-DD-YYYY").year();
quarterList = []
for (var i = lowerRange; i <= upperRange; i++) {
quarterList.push('Q' + i + '_' + year);
}
//get list of year strings
lowerRange = moment(dateStart, "MM-DD-YYYY").year();
upperRange = moment(dateEnd, "MM-DD-YYYY").year();
yearList = []
for (var i = lowerRange; i <= upperRange; i++) {
yearList.push('Y' + i + '_' + year);
}
console.log(weekList);
console.log(monthList);
console.log(quarterList);
console.log(yearList);
答案 0 :(得分:0)
它只适用于weekList,但你应该能够找到其余部分:
lowerRange = moment(dateStart, "MM-DD-YYYY").week();
upperRange = moment(dateEnd, "MM-DD-YYYY").week();
year = moment(dateStart, "MM-DD-YYYY").year();
year2 = moment(dateEnd, "MM-DD-YYYY").year();
//add extra weeks to upperRange if the date range > 12 months
upperRange += (year2-year)*52-lowerRange;
weekList = []
for (var i = lowerRange; i <= upperRange; i++) {
//some fix to show the year
weekList.push('W' + (i-lowerRange) + '_' + (year+Math.floor((i-lowerRange)/12)));
}
答案 1 :(得分:0)
要使您的计算在多年内发挥作用,您应该不是基于endDate,而是基于两个日期之间的持续时间。为此,您可以使for循环从startDate转到startDate + duration。
dateStart = "01-01-2018";
dateEnd = "03-31-2019";
start = moment(dateStart, "MM-DD-YYYY")
end = moment(dateEnd, "MM-DD-YYYY")
lowerRange = Math.floor(moment(dateStart, "MM-DD-YYYY").dayOfYear()/7);
// calculate the number of weeks between the two dates
numberOfWeeks = end.diff(start, 'weeks');
year = moment(dateStart, "MM-DD-YYYY").year();
weekListA = []
for (var i = lowerRange; i <= lowerRange + numberOfWeeks; i++) {
weekListA.push('W' + (i%52 +1) + '_' + (year+ Math.floor(i/52)));
}
console.log(weekListA);
我补充说:
numberOfWeeks
; + (i%52 +1)
,得到周数(你必须写+1才能从0开始。由于这个约束,你必须使用Math.floor()代替在计算lowerRange时使用Math.ceil(); + Math.floor(i/52)
,以增加年份的数量; 我让你检查是否涵盖了所有案件(超过2年的日期,包括或排除的日期等)