Mateus Vitali
Mateus Vitali

Reputation: 159

Moment.js - Strange behavior when added days

I'm trying to increase 1 day in a loop in October (2016) but there was a strange behavior. When arriving on 10/15/2016 it does not increase 1 day, only 23 hours.

var date = moment("2016-09-25");
for (var j = 0; j < 42; j++) {
    console.log('before: ' + date.format());
    date = date.clone();
    date.add(1, 'day');
    console.log('after: ' + date.format());
}

console:

after: 2016-10-13T00:00:00-03:00

before: 2016-10-13T00:00:00-03:00

after: 2016-10-14T00:00:00-03:00

before: 2016-10-14T00:00:00-03:00

after: 2016-10-15T00:00:00-03:00

before: 2016-10-15T00:00:00-03:00

after: 2016-10-15T23:00:00-03:00

before: 2016-10-15T23:00:00-03:00

after: 2016-10-16T23:00:00-02:00

before: 2016-10-16T23:00:00-02:00

https://jsfiddle.net/7bxqo0m2/

Upvotes: 0

Views: 81

Answers (2)

Mateus Vitali
Mateus Vitali

Reputation: 159

The problem here is that Brazil does daylight savings at midnight, which confuses the concept of a "day". What Moment is trying to do is set the day to the current current time with the day = original day + 1.

The problem is that when it creates a JS date as 2013-10-20T00:00:00, the underlying date library gets confused, because that time doesn't exist in Brazil. The behavior varies a bit browser to browser, but here's the behavior in Node and Chrome:

d = moment('2016-10-19').toDate(); //get the native date object
d.setDate(18); //use the native API to set the date
d; // Fri Oct 18 2016 00:00:00 GMT-0300 (BRT), so works fine

//but
d = moment('2016-10-19').toDate(); //get the native date object
d.setDate(20);
d; // Sat Oct 19 2016 23:00:00 GMT-0300 (BRT), WTF?

I changed my start date for endOf() and solved the problem

date.endOf('day');

Upvotes: 1

nikjohn
nikjohn

Reputation: 21832

That is because October is when Daylight Savings Time comes into effect, thereby offsetting your time by 1 hour

Please read about moment's constructor here and look at moment.utc and moment.parseZone

Upvotes: 4

Related Questions