Skip to content

Commit

Permalink
fix: fix week() error near the end of the year
Browse files Browse the repository at this point in the history
  • Loading branch information
iamkun committed Jul 3, 2018
1 parent 03bb181 commit fa03689
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 7 deletions.
17 changes: 10 additions & 7 deletions src/plugin/weekOfYear/index.js
Original file line number Diff line number Diff line change
@@ -1,12 +1,15 @@
import { MILLISECONDS_A_DAY } from '../../constant'
import { MS, Y, D, W } from '../../constant'

export default (o, c) => {
export default (o, c, d) => {
const proto = c.prototype
proto.week = function () {
const day = this.$W || 7 // Return sunday as 7
// Create date at nearest thursday
const ins = new Date(this.$y, this.$M, (this.$D - day) + 4)
const yearStart = new Date(Date.UTC(this.$y, 0, 1)) // Get first day of year
return Math.ceil((((ins - yearStart) / MILLISECONDS_A_DAY) + 1) / 7) // Calculate weeks
const endOfYear = this.endOf(Y)
if (endOfYear.day() !== 6 && this.month() === 11 && (31 - this.date()) <= endOfYear.day()) {
return 1
}
const startOfYear = d(this.$d).startOf(Y)
const compareDay = startOfYear.subtract(startOfYear.day(), D).subtract(1, MS)
const diffInWeek = this.diff(compareDay, W, true)
return Math.ceil(diffInWeek)
}
}
2 changes: 2 additions & 0 deletions test/plugin/weekOfYear.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,5 +14,7 @@ afterEach(() => {
})

it('Week of year', () => {
const day = '2018-12-31T10:59:09+08:00'
expect(dayjs(day).week()).toBe(moment(day).week())
expect(dayjs().week()).toBe(moment().week())
})

0 comments on commit fa03689

Please sign in to comment.