From 08d518cae6f905cd136eb5ca35fc40aa62c62017 Mon Sep 17 00:00:00 2001 From: Ferdinand Prantl Date: Sat, 29 Sep 2018 12:59:07 +0200 Subject: [PATCH] fix: Do not store the Date object instance passed to the dayjs function If the Date object instance is modified later, it will affect the the dayjs instance too. It will modify its internal this.$d object and make it inconsistent with the other this.$* variables. It will break the immutability of dayjs instances. --- src/index.js | 17 +++++++++++------ test/parse.test.js | 8 ++++++++ 2 files changed, 19 insertions(+), 6 deletions(-) diff --git a/src/index.js b/src/index.js index c09b4fe13..e31f73fcd 100644 --- a/src/index.js +++ b/src/index.js @@ -36,11 +36,15 @@ const dayjs = (date, c) => { } } const cfg = c || {} + if (date instanceof Date && cfg.cloneDate !== false) { + date = new Date(date) + } cfg.date = date return new Dayjs(cfg) // eslint-disable-line no-use-before-define } -const wrapper = (date, instance) => dayjs(date, { locale: instance.$L, utc: instance.$u }) +const wrapper = (date, instance, cloneDate) => + dayjs(date, { locale: instance.$L, utc: instance.$u, cloneDate }) const Utils = U // for plugin use Utils.parseLocale = parseLocale @@ -184,16 +188,17 @@ class Dayjs { const date = this.$u ? new Date(Date.UTC(this.$y, m, d)) : new Date(this.$y, m, d) - const ins = wrapper(date, this) + const ins = wrapper(date, this, false) return isStartOf ? ins : ins.endOf(C.D) } const instanceFactorySet = (slice) => { const argumentStart = [0, 0, 0, 0] const argumentEnd = [23, 59, 59, 999] - return wrapper(this.toDate()[setMethods[slice]].apply( // eslint-disable-line prefer-spread - this.toDate(), + const date = this.toDate() + return wrapper(date[setMethods[slice]].apply( // eslint-disable-line prefer-spread + date, isStartOf ? argumentStart.slice(slice) : argumentEnd.slice(slice) - ), this) + ), this, false) } switch (unit) { case C.Y: @@ -443,7 +448,7 @@ class Dayjs { } clone() { - return wrapper(this.toDate(), this) + return wrapper(this.toDate(), this, false) } toDate() { diff --git a/test/parse.test.js b/test/parse.test.js index 302e5c757..864b5a2db 100644 --- a/test/parse.test.js +++ b/test/parse.test.js @@ -107,6 +107,14 @@ it('Creating a new instance from another instance retains the UTC mode', () => { expect(instance.minute()).toEqual(source.minute()) }) +it('Original Date object does not affect the dayjs instance', () => { + const original = new Date() + const instance = dayjs(original) + const internal = instance.toDate() + original.setTime(original.getTime() - 3600000) + expect(instance.toDate()).toEqual(internal) +}) + it('Clone not affect each other', () => { const base = dayjs(20170101) const year = base.year()