icambron / twix.js

:hourglass::left_right_arrow: A date range plugin for moment.js
https://isaaccambron.com/twix.js/
MIT License
379 stars 54 forks source link

Inconsitent handling of Date objects as input between twix and moment. #99

Closed fire-the-missiles closed 7 years ago

fire-the-missiles commented 7 years ago

Can you please make the handling of Date objects as input in twix consitent with moment. The behaviour of moment is reasonable. Twix does not have reasonable behaviour.

Examples:

>moment(new Date('2017-01-03T00:00:00.000Z')).toDate();
2017-01-03T00:00:00.000Z
>moment.twix(new Date('2017-01-03T00:00:00.000Z'), new Date('2017-01-03T00:00:00.000Z')).toArray('day').map(x => x.toDate()); /* Swedish time zone used. */
[ 2017-01-02T23:00:00.000Z ]
icambron commented 7 years ago

Edit: I screwed up my first pass at this. Edited to reflect that.

That's not a difference in behavior. Twix calls moment() on its input, so the endpoints of the Twix range are actually the same as if you'd created them like you did that Moment instance. The problem is Moment's toDate() doesn't do what you think it does. It isn't telling you the beginning of the current day; it's converting back to a Javascript Date object. It's just echoing back the time you gave it. For example, inputing a time other than midnight:

> moment(new Date('2017-01-03T03:00:00.000Z')).toDate()
//=> 2017-01-03T03:00:00.000Z

If you want the beginning of the day in Moment, you'd do this:

> moment(new Date('2017-01-03T00:00:00.000Z')).startOf('day').toDate()
//=> 2017-01-02T05:00:00.000Z

which returns the local start of the day, just like in your Twix example. So the behaviors are the same.

If you want Twix (or Moment) to work in UTC, you need to tell it that with either .utc() or #utc():

> moment.utc('2017-01-03T00:00:00.000Z').startOf('day').toDate()
//=> 2017-01-03T00:00:00.000Z

moment.twix(moment.utc('2017-01-03T00:00:00.000Z'),  moment.utc('2017-01-03T00:00:00.000Z')).toArray('day').map(x => x.toDate());
//=> [ 2017-01-03T00:00:00.000Z ]