我有条件使用javascript在开始结束日期之间每6个月拆分一次。请考虑以下示例
开课日期:11/08/2018(mm / dd / yyyy) 截止日期:01/20/2020
需要跟随分手
lineSpacingExtra
请告知
答案 0 :(得分:1)
希望这有助于http://plnkr.co/edit/hgEyiLyrX3Lfa7NJTeaL:
var startDate = moment('11/08/2018');
var endDate = moment('01/20/2020');
function splitHalfYear(startDate, endDate) {
var startMonth = startDate.month();
var currentDate = moment(startDate);
var returner = [];
if (startMonth < 6) {
currentDate = currentDate.startOf('year').add('month', 6);
}
else {
currentDate = currentDate.startOf('year').add('year', 1);
}
returner.push({from: startDate, to: moment(currentDate).subtract('second', 1)});
while(currentDate <= endDate) {
var from = moment(currentDate);
currentDate = currentDate.add('month', 6);
if (currentDate.isAfter(endDate)) {
returner.push({from: from, to: endDate});
}
else {
returner.push({from: from, to: moment(currentDate).subtract('second', 1)});
}
}
return returner;
}
var dates = splitHalfYear(startDate, endDate);
dates.forEach(function(interval) {
document.write(interval.from.format() +' - ');
document.write(interval.to.format() + '<br>');
})
答案 1 :(得分:0)
您可以轻松完成momentjs
,如下所示:
var beforeSixMonths = moment().subtract(6,'months');
var today = moment();
// and use like below for your other needs
var afterSixMonths = moment().add(6,'months');
有关详细信息,请参阅docs
答案 2 :(得分:0)
这是一个迭代Date的简单代码段。然后,您可以添加所需的代码:
var start = "11/08/2018";
var end = "01/20/2020";
var sd = new Date(start); //sd from starting date
var ed = new Date(end); //ed from end date
var months_interval = 6;
console.log("----------");
while(true){
if(sd>ed){ //if adding 6 months is higher than end date.
console.log("from: "+sd);
console.log("to: "+ed);
break;
}else{
console.log("from: "+sd);
sd.setMonth(sd.getMonth()+months_interval); //add 6 months
console.log("to: "+sd);
}
}
希望有所帮助:)
编辑:如果你想要递归,这是另一个代码:
var start = "11/08/2018";
var end = "01/20/2020";
var sd = new Date(start); //sd from starting date
var ed = new Date(end); //ed from end date
var months_interval = 6;
console.log("----------");
iterate(sd,ed);
function iterate(sd,ed){
if(sd>ed){
console.log("FROM: "+sd+" TO: "+ed);
return;
}else{
var new_sd = new Date(sd)
new_sd.setMonth(new_sd.getMonth()+months_interval);
console.log("FROM: "+sd+" TO: "+new_sd);
iterate(new_sd,ed);
}
}