Skip to content

Commit

Permalink
fix: Handle locale in WeekOfYear plugin (#658)
Browse files Browse the repository at this point in the history
  • Loading branch information
g1eny0ung authored and iamkun committed Aug 19, 2019
1 parent 572e5a4 commit 0e45b0a
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 2 deletions.
13 changes: 11 additions & 2 deletions src/plugin/weekOfYear/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,22 @@ export default (o, c, d) => {
if (week !== null) {
return this.add((week - this.week()) * 7, 'day')
}

const weekStart = this.$locale().weekStart || 0

// d(this) clone is for badMutable plugin
const endOfYear = d(this).endOf(Y)
if (endOfYear.day() !== 6 && this.month() === 11 && (31 - this.date()) <= endOfYear.day()) {
if (
weekStart === 0 &&
endOfYear.day() !== 6 &&
this.month() === 11 &&
31 - this.date() <= endOfYear.day()
) {
return 1
}

const startOfYear = d(this).startOf(Y)
const compareDay = startOfYear.subtract(startOfYear.day(), D).subtract(1, MS)
const compareDay = startOfYear.subtract(startOfYear.day() - weekStart, D).subtract(1, MS)
const diffInWeek = this.diff(compareDay, W, true)
return Math.ceil(diffInWeek)
}
Expand Down
15 changes: 15 additions & 0 deletions test/plugin/weekOfYear.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import moment from 'moment'
import MockDate from 'mockdate'
import dayjs from '../../src'
import weekOfYear from '../../src/plugin/weekOfYear'
import '../../src/locale/en-gb'

dayjs.extend(weekOfYear)

Expand All @@ -14,6 +15,8 @@ afterEach(() => {
})

it('Week of year', () => {
dayjs.locale('en')

const day = '2018-12-31T10:59:09+08:00'
const week = 27
expect(dayjs(day).week()).toBe(moment(day).week())
Expand All @@ -24,3 +27,15 @@ it('Week of year', () => {
expect(dayjs().weeks(55).week()).toBe(moment().weeks(55).week())
expect(dayjs().weeks()).toBe(moment().weeks())
})

it('Week of year with locale', () => {
dayjs.locale('en-gb')
moment.locale('en-gb')

const day = '2019-07-28'
expect(dayjs(day).week()).toBe(moment(day).week())

// Edges
expect(dayjs('2018-12-30').week()).toBe(moment('2018-12-30').week())
expect(dayjs('2019-12-29').week()).toBe(moment('2019-12-29').week())
})

0 comments on commit 0e45b0a

Please sign in to comment.