Skip to content

Commit 03bb181

Browse files
authored
Merge pull request #259 from naulacambra/master
feat: Added method to retrieve week of the year
2 parents 52b6355 + 0869dfa commit 03bb181

File tree

3 files changed

+41
-0
lines changed

3 files changed

+41
-0
lines changed

docs/en/Plugin.md

+11
Original file line numberDiff line numberDiff line change
@@ -144,6 +144,17 @@ List of added formats:
144144
| `BBBB` | 2561 | Full BE Year (Year + 543) |
145145
| `BB` | 61 | 2-digit of BE Year |
146146

147+
### WeekOfYear
148+
- WeekOfYear adds `.week()` API to returns a `number` indicating the `Dayjs`'s week of the year.
149+
150+
```javascript
151+
import weekOfYear from 'dayjs/plugin/weekOfYear'
152+
153+
dayjs.extend(weekOfYear)
154+
155+
dayjs('06/27/2018').week() // 26
156+
```
157+
147158
## Customize
148159

149160
You could build your own Day.js plugin to meet different needs.

src/plugin/weekOfYear/index.js

+12
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
import { MILLISECONDS_A_DAY } from '../../constant'
2+
3+
export default (o, c) => {
4+
const proto = c.prototype
5+
proto.week = function () {
6+
const day = this.$W || 7 // Return sunday as 7
7+
// Create date at nearest thursday
8+
const ins = new Date(this.$y, this.$M, (this.$D - day) + 4)
9+
const yearStart = new Date(Date.UTC(this.$y, 0, 1)) // Get first day of year
10+
return Math.ceil((((ins - yearStart) / MILLISECONDS_A_DAY) + 1) / 7) // Calculate weeks
11+
}
12+
}

test/plugin/weekOfYear.test.js

+18
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,18 @@
1+
import moment from 'moment'
2+
import MockDate from 'mockdate'
3+
import dayjs from '../../src'
4+
import weekOfYear from '../../src/plugin/weekOfYear'
5+
6+
dayjs.extend(weekOfYear)
7+
8+
beforeEach(() => {
9+
MockDate.set(new Date())
10+
})
11+
12+
afterEach(() => {
13+
MockDate.reset()
14+
})
15+
16+
it('Week of year', () => {
17+
expect(dayjs().week()).toBe(moment().week())
18+
})

0 commit comments

Comments
 (0)