Skip to content

Commit

Permalink
Merge pull request #57 from xx45/dev
Browse files Browse the repository at this point in the history
 fix(startOf): startOf date equals to day
  • Loading branch information
iamkun authored Apr 25, 2018
2 parents 4abede4 + b517622 commit dbe15c2
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 12 deletions.
30 changes: 21 additions & 9 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -91,25 +91,37 @@ class Dayjs {

startOf(units, isStartOf = true) { // isStartOf -> endOf
const unit = Utils.prettyUnit(units)
const instanceFactory = (d, m, y = this.$y, isEnd = false) => {
const instanceFactory = (d, m, y = this.$y) => {
const ins = new Dayjs(new Date(y, m, d))
return isEnd ? ins.endOf(C.D) : ins
return isStartOf ? ins : ins.endOf(C.D)
}
const instanceFactorySet = (method, slice) => {
const argumentStart = [0, 0, 0, 0]
const argumentEnd = [23, 59, 59, 999]
return new Dayjs(Date()[method].apply(

This comment has been minimized.

Copy link
@adamwirth

adamwirth Apr 25, 2018

line 101 needs to be changed to return new Dayjs(new Date()[method].apply( instead of just (Date()[

this.toDate(),
isStartOf ? argumentStart.slice(slice) : argumentEnd.slice(slice)
))
}
switch (unit) {
case C.Y:
return isStartOf ? instanceFactory(1, 0) :
instanceFactory(31, 11, this.$y, true)
instanceFactory(31, 11, this.$y)
case C.M:
return isStartOf ? instanceFactory(1, this.$M) :
instanceFactory(0, this.$M + 1, this.$y, true)
instanceFactory(0, this.$M + 1, this.$y)
case C.W:
return isStartOf ? instanceFactory(this.$D - this.$W, this.$M) :
instanceFactory(this.$D + (6 - this.$W), this.$M, this.$y, true)
instanceFactory(this.$D + (6 - this.$W), this.$M, this.$y)
case C.D:
if (isStartOf) {
return new Dayjs(this.toDate().setHours(0, 0, 0, 0))
}
return new Dayjs(this.toDate().setHours(23, 59, 59, 999))
case C.DATE:
return instanceFactorySet('setHours', 0)
case C.H:
return instanceFactorySet('setMinutes', 1)
case C.MIN:
return instanceFactorySet('setSeconds', 2)
case C.S:
return instanceFactorySet('setMilliseconds', 3)
default:
return this.clone()
}
Expand Down
7 changes: 4 additions & 3 deletions test/manipulate.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,10 +12,11 @@ afterEach(() => {

describe('StartOf EndOf', () => {
it('StartOf EndOf Year ... with s and upper case', () => {
const testArr = ['Year', 'year', 'YearS', 'month', 'day', 'week']
const testArr = ['Year', 'year', 'YearS', 'month', 'day', 'date',
'week', 'hour', 'minute', 'second']
testArr.forEach((d) => {
expect(dayjs().startOf(d).unix()).toBe(moment().startOf(d).unix())
expect(dayjs().endOf(d).unix()).toBe(moment().endOf(d).unix())
expect(dayjs().startOf(d).valueOf()).toBe(moment().startOf(d).valueOf())
expect(dayjs().endOf(d).valueOf()).toBe(moment().endOf(d).valueOf())
})
})

Expand Down

0 comments on commit dbe15c2

Please sign in to comment.