【问题标题】:How to create date occurrence between two dates by giving days gap?如何通过给出天间隔来创建两个日期之间的日期发生?
【发布时间】:2019-12-26 04:43:53
【问题描述】:

我有以下数据:

1 年合同

Start Date: 01-01-2019

End Date: 31-12-2019

开始日期和结束日期之间的 15 天间隔不包括所有星期五

确切的预期输出不包括所有星期五

19-01-2019 //exclude Fridays then got 19 jan 2019
-----------
05-02-2019 //after 15 days
-----------
23-02-2019 //after 15 days
-------------
keep on adding.. hit until end month 12-2019

如何生成它?有更好的方法吗?

var start = new Date("2019-01-01");
var end = new Date("2019-12-31");

while (start <= end) {
    console.log( new Date(start) );
    start.setMonth( start.getMonth() + 1 );
}

【问题讨论】:

    标签: javascript jquery date datepicker


    【解决方案1】:

    从您的用例来看,周五似乎是非工作日,您希望根据开始日期打印第 15 天。

    Date.prototype.addDays = function(days) {
    var date = new Date(this.valueOf());
    date.setDate(date.getDate() + days);
    return date; }
    
    function printNextPeriod(startDate, endDate, periodInDays) {
    var numWorkDays = 0;
    var currentDate = new Date(startDate);
    while (numWorkDays < periodInDays && currentDate <= endDate) {
        currentDate = currentDate.addDays(1);
        // Skips friday
        if (currentDate.getDay() !== 5) {
            numWorkDays++;
        }
        if (numWorkDays == periodInDays) {
            numWorkDays = 0;
            console.log(currentDate);
        }
    } }
    

    var start = new Date("2019-01-01"); var end = new Date("2019-12-31"); var period = 15; printNextPeriod(start, end, period);

    【讨论】:

    • 太棒了!!!..如果不显示 sat 和 GMT,我将如何格式化 2019 年 1 月 19 日的格式
    • 我想在一个 html 表格中显示这个,列名称为 Date 然后值将是 19-Jan-2019、05-Feb-2019...等等
    • 是否也可以跳过假期??假设我在数据库中有一组假期列表。假期不会出现在结果日期。我想跳过假期日期并跳到下一个日期是很好
    • 如果假期是 2019 年 1 月 19 日,则跳过此日期并需要显示 2019 年 1 月 20 日(不包括周五)..那么接下来的 15 天将是 2019 年 2 月 6 日(15 天从1 月 21 日)
    • 例如 var holiday = array("2019-01-19", "2019-02-22", "2019-12-25"");
    猜你喜欢
    • 2020-01-31
    • 2015-08-06
    • 2021-09-28
    • 1970-01-01
    • 1970-01-01
    • 2012-06-28
    • 1970-01-01
    • 2012-03-26
    • 1970-01-01
    相关资源
    最近更新 更多