Skip to content

Commit

Permalink
fix: Fix relativeTime Plugin .FromNow() result error in UTC mode
Browse files Browse the repository at this point in the history
  • Loading branch information
g1eny0ung authored and iamkun committed Jul 31, 2019
1 parent cc1f15f commit a385d5c
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 3 deletions.
7 changes: 5 additions & 2 deletions src/plugin/relativeTime/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -59,10 +59,13 @@ export default (o, c, d) => {
proto.from = function (input, withoutSuffix) {
return fromTo(input, withoutSuffix, this)
}

const makeNow = thisDay => (thisDay.$u ? d.utc() : d())

proto.toNow = function (withoutSuffix) {
return this.to(d(), withoutSuffix)
return this.to(makeNow(this), withoutSuffix)
}
proto.fromNow = function (withoutSuffix) {
return this.from(d(), withoutSuffix)
return this.from(makeNow(this), withoutSuffix)
}
}
25 changes: 24 additions & 1 deletion test/plugin/relativeTime.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import MockDate from 'mockdate'
import moment from 'moment'
import dayjs from '../../src'
import relativeTime from '../../src/plugin/relativeTime'
import utc from '../../src/plugin/utc'

dayjs.extend(relativeTime)

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


it('Time to now', () => {
expect(dayjs().toNow()).toBe(moment().toNow())
expect(dayjs().toNow(true)).toBe(moment().toNow(true))
Expand All @@ -82,3 +82,26 @@ it('Time to X', () => {
// past date
expect(dayjs().to(dayjs().subtract(3, 'year'))).toBe(moment().to(moment().subtract(3, 'year')))
})

// https://github.com/iamkun/dayjs/issues/646
it('Time from now with UTC', () => {
dayjs.extend(utc)

expect(dayjs.utc().fromNow()).toBe(moment.utc().fromNow())

const currentTime = new Date()
const currentTimestamp = currentTime.getTime()
const currentTimestampAfter37hrs = currentTimestamp + (37 * 60 * 60 * 1000)

let dutc = dayjs.utc(currentTimestampAfter37hrs)
let mutc = moment.utc(currentTimestampAfter37hrs)

expect(dutc.fromNow()).toBe(mutc.fromNow())

// More precise
const currentTimestampAfter36hrs = currentTimestamp + (36.0001 * 60 * 60 * 1000)
dutc = dayjs.utc(currentTimestampAfter36hrs)
mutc = moment.utc(currentTimestampAfter36hrs)

expect(dutc.fromNow()).toBe(mutc.fromNow())
})

0 comments on commit a385d5c

Please sign in to comment.