Skip to content

Commit a385d5c

Browse files
g1eny0ungiamkun
authored andcommitted
fix: Fix relativeTime Plugin .FromNow() result error in UTC mode
1 parent cc1f15f commit a385d5c

File tree

2 files changed

+29
-3
lines changed

2 files changed

+29
-3
lines changed

src/plugin/relativeTime/index.js

+5-2
Original file line numberDiff line numberDiff line change
@@ -59,10 +59,13 @@ export default (o, c, d) => {
5959
proto.from = function (input, withoutSuffix) {
6060
return fromTo(input, withoutSuffix, this)
6161
}
62+
63+
const makeNow = thisDay => (thisDay.$u ? d.utc() : d())
64+
6265
proto.toNow = function (withoutSuffix) {
63-
return this.to(d(), withoutSuffix)
66+
return this.to(makeNow(this), withoutSuffix)
6467
}
6568
proto.fromNow = function (withoutSuffix) {
66-
return this.from(d(), withoutSuffix)
69+
return this.from(makeNow(this), withoutSuffix)
6770
}
6871
}

test/plugin/relativeTime.test.js

+24-1
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import MockDate from 'mockdate'
22
import moment from 'moment'
33
import dayjs from '../../src'
44
import relativeTime from '../../src/plugin/relativeTime'
5+
import utc from '../../src/plugin/utc'
56

67
dayjs.extend(relativeTime)
78

@@ -70,7 +71,6 @@ it('Time from now', () => {
7071
expect(dayjs().fromNow(true)).toBe(moment().fromNow(true))
7172
})
7273

73-
7474
it('Time to now', () => {
7575
expect(dayjs().toNow()).toBe(moment().toNow())
7676
expect(dayjs().toNow(true)).toBe(moment().toNow(true))
@@ -82,3 +82,26 @@ it('Time to X', () => {
8282
// past date
8383
expect(dayjs().to(dayjs().subtract(3, 'year'))).toBe(moment().to(moment().subtract(3, 'year')))
8484
})
85+
86+
// https://github.com/iamkun/dayjs/issues/646
87+
it('Time from now with UTC', () => {
88+
dayjs.extend(utc)
89+
90+
expect(dayjs.utc().fromNow()).toBe(moment.utc().fromNow())
91+
92+
const currentTime = new Date()
93+
const currentTimestamp = currentTime.getTime()
94+
const currentTimestampAfter37hrs = currentTimestamp + (37 * 60 * 60 * 1000)
95+
96+
let dutc = dayjs.utc(currentTimestampAfter37hrs)
97+
let mutc = moment.utc(currentTimestampAfter37hrs)
98+
99+
expect(dutc.fromNow()).toBe(mutc.fromNow())
100+
101+
// More precise
102+
const currentTimestampAfter36hrs = currentTimestamp + (36.0001 * 60 * 60 * 1000)
103+
dutc = dayjs.utc(currentTimestampAfter36hrs)
104+
mutc = moment.utc(currentTimestampAfter36hrs)
105+
106+
expect(dutc.fromNow()).toBe(mutc.fromNow())
107+
})

0 commit comments

Comments
 (0)