Skip to content

Problems with midnight on addWorkingTime #52

@giacomomichelon-centropaghe

Description

Hi,
i have an issue with the following situation:

    describe('Midnight problems', function () {

        it('Add times between days', function () {

            moment.locale('en', {
                workinghours: {
                    0: null,
                    1: ['16:00:00', '24:00:00'],
                    2: ['16:00:00', '24:00:00'],
                    3: ['16:00:00', '24:00:00'],
                    4: ['16:00:00', '24:00:00'],
                    5: ['16:00:00', '24:00:00'],
                    6: null
                }
            });

            moment('2022-03-23T22:00:00.000').addWorkingTime(121, 'minutes').format(full).should.equal('2022-03-24 16:01:00.000');

        });
        
    });

this is a test that i added to show the issue, if you try to run it it goes on an infinite loop,

i have found a fix to that:

function addUnit(unit) {
    return function (n, d) {
        if (!d.isWorkingTime()) {
            d = d.nextWorkingTime();
        }
        var i = 0;
        while (n > 0) {
            var segment = openingTimes(d)[i];
            if (!segment || d.isBefore(segment[0])) {
                i = 0;
                d = d.nextWorkingTime();
                continue;
            }
            if (d.isAfter(segment[1])) {
                i++;
                continue;
            }
            var jump = segment[1].diff(d, unit);
            if (jump > n) {
              jump = n;
            }
            if (jump < 1) {
              jump = 1;
            }
            var then = d.clone().add(jump, unit);
            n -= jump;
            if (then.isSameOrBefore(segment[1])) {
                d = d.add(jump, unit);
            } else {
                var next = then.nextWorkingTime();
                var diff = then.diff(segment[1], unit, true);
                d = next.add(diff,unit);
            }
        }
        return d;
    };
}

the fix is right before the first "continue" statement, i would like to push the fix, but i am unable to do that

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions