Skip to content

Commit

Permalink
fix: Add weekday (locale aware day of week) plugin
Browse files Browse the repository at this point in the history
fix #559
  • Loading branch information
iamkun committed Apr 15, 2019
1 parent ffffacf commit 6414395
Show file tree
Hide file tree
Showing 3 changed files with 68 additions and 0 deletions.
13 changes: 13 additions & 0 deletions src/plugin/weekday/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export default (o, c) => {
const proto = c.prototype
proto.weekday = function (input) {
const weekStart = this.$locale().weekStart || 0
const { $W } = this
const weekday = ($W < weekStart ? $W + 7 : $W) - weekStart
if (this.$utils().u(input)) {
return weekday
}
return this.subtract(weekday, 'day').add(input, 'day')
}
}

43 changes: 43 additions & 0 deletions test/plugin/weekday.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import MockDate from 'mockdate'
import moment from 'moment'
import dayjs from '../../src'
import weekday from '../../src/plugin/weekday'
import '../../src/locale/zh-cn'
import '../../src/locale/ar'

dayjs.extend(weekday)

beforeEach(() => {
MockDate.set(new Date())
})

afterEach(() => {
MockDate.reset()
moment.locale('en')
dayjs.locale('en')
})

it('Sunday is the first day of the week', () => {
expect(dayjs().weekday()).toBe(moment().weekday())
expect(dayjs().weekday(0).date()).toBe(moment().weekday(0).date())
expect(dayjs().weekday(-7).format()).toBe(moment().weekday(-7).format())
expect(dayjs().weekday(7).format()).toBe(moment().weekday(7).format())
})

it('Monday is the first day of the week', () => {
moment.locale('zh-cn')
dayjs.locale('zh-cn')
expect(dayjs().weekday()).toBe(moment().weekday())
expect(dayjs().weekday(0).date()).toBe(moment().weekday(0).date())
expect(dayjs().weekday(-7).format()).toBe(moment().weekday(-7).format())
expect(dayjs().weekday(7).format()).toBe(moment().weekday(7).format())
})

it('Saturday is the first day of the week', () => {
moment.locale('ar')
dayjs.locale('ar')
expect(dayjs().weekday()).toBe(moment().weekday())
expect(dayjs().weekday(0).date()).toBe(moment().weekday(0).date())
expect(dayjs().weekday(-7).valueOf()).toBe(moment().weekday(-7).valueOf())
expect(dayjs().weekday(7).valueOf()).toBe(moment().weekday(7).valueOf())
})
12 changes: 12 additions & 0 deletions types/plugin/weekday.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { PluginFunc } from 'dayjs'

declare const plugin: PluginFunc
export = plugin

declare module 'dayjs' {
interface Dayjs {
weekday(): number

weekday(value: number): Dayjs
}
}

0 comments on commit 6414395

Please sign in to comment.