Skip to content

Commit

Permalink
Showing 3 changed files with 41 additions and 0 deletions.
11 changes: 11 additions & 0 deletions docs/en/Plugin.md
Original file line number Diff line number Diff line change
@@ -144,6 +144,17 @@ List of added formats:
| `BBBB` | 2561 | Full BE Year (Year + 543) |
| `BB` | 61 | 2-digit of BE Year |

### WeekOfYear
- WeekOfYear adds `.week()` API to returns a `number` indicating the `Dayjs`'s week of the year.

```javascript
import weekOfYear from 'dayjs/plugin/weekOfYear'

dayjs.extend(weekOfYear)

dayjs('06/27/2018').week() // 26
```

## Customize

You could build your own Day.js plugin to meet different needs.
12 changes: 12 additions & 0 deletions src/plugin/weekOfYear/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { MILLISECONDS_A_DAY } from '../../constant'

export default (o, c) => {
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
}
}
18 changes: 18 additions & 0 deletions test/plugin/weekOfYear.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import moment from 'moment'
import MockDate from 'mockdate'
import dayjs from '../../src'
import weekOfYear from '../../src/plugin/weekOfYear'

dayjs.extend(weekOfYear)

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

afterEach(() => {
MockDate.reset()
})

it('Week of year', () => {
expect(dayjs().week()).toBe(moment().week())
})

0 comments on commit 03bb181

Please sign in to comment.