gpt4 book ai didi

javascript - 查找日期之间所有 6 个月的开始日期和结束日期 javascript

转载 作者:行者123 更新时间:2023-11-27 23:39:48 25 4
gpt4 key购买 nike

我遇到了使用 javascript 在开始结束日期之间每 6 个月进行一次分割的情况。考虑以下示例,

开始日期:11/08/2018(月/日/年)结束日期:2020年1月20日

分手后需要

From        To          Note
11/08/2018 12/31/2018 here 11/08/2018 and 12/31/2018 comes between July to Dec which is second half of year
01/01/2019 06/30/2019 here 01/01/2019 and 06/30/2019 comes between Jan - June which is first half of year
07/01/2019 12/31/2019 here 07/01/2019 and 12/31/2019 comes between July to Dec which is second half of year
01/01/2020 01/20/2020 here 01/01/2020 and 01/20/2020 comes between Jan - Jun which is first half year

请指教

最佳答案

希望这有帮助 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>');
})

关于javascript - 查找日期之间所有 6 个月的开始日期和结束日期 javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33775896/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com