Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add isoWeekYear setter for Day.js ISO week handling #2800

Open
wants to merge 4 commits into
base: dev
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/plugin/isoWeek/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,23 @@ export default (o, c, d) => {

const proto = c.prototype

proto.isoWeekYear = function () {
proto.isoWeekYear = function (year) {
if (!this.$utils().u(year)) {
const currentIsoWeek = this.isoWeek()
const currentIsoWeekday = this.isoWeekday()

const newYearThursday = getYearFirstThursday(year, this.$u)

const newDate = newYearThursday
.add(currentIsoWeek - 1, W)
.isoWeekday(currentIsoWeekday)

this.$d = newDate.toDate()
this.init()

return this
}

const nowWeekThursday = getCurrentWeekThursday(this)
return nowWeekThursday.year()
}
Expand Down
42 changes: 42 additions & 0 deletions test/plugin/isoWeek.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,48 @@ it('get isoWeekYear', () => {
expect(dayjs().isoWeekYear()).toBe(moment().isoWeekYear())
})

it('2024-12-29 to ISO Year 2025, ISO Week 1, then +1 week', () => {
const testCase = {
initialDate: '2024-12-29',
targetIsoYear: 2025,
targetIsoWeek: 1,
addWeeks: 1
}

const momentResult = moment(testCase.initialDate)
.isoWeekYear(testCase.targetIsoYear)
.isoWeek(testCase.targetIsoWeek)
.add(testCase.addWeeks, 'week')

const dayjsResult = dayjs(testCase.initialDate)
.isoWeekYear(testCase.targetIsoYear)
.isoWeek(testCase.targetIsoWeek)
.add(testCase.addWeeks, 'week')

expect(dayjsResult.valueOf()).toBe(momentResult.valueOf())
})

it('2024-01-01 to ISO Year 2023, ISO Week 2, then -1 week', () => {
const testCase = {
initialDate: '2024-01-01',
targetIsoYear: 2023,
targetIsoWeek: 52,
weeks: 1
}

const momentResult = moment(testCase.initialDate)
.isoWeekYear(testCase.targetIsoYear)
.isoWeek(testCase.targetIsoWeek)
.subtract(testCase.weeks, 'week')

const dayjsResult = dayjs(testCase.initialDate)
.isoWeekYear(testCase.targetIsoYear)
.isoWeek(testCase.targetIsoWeek)
.subtract(testCase.weeks, 'week')

expect(dayjsResult.valueOf()).toBe(momentResult.valueOf())
})

it('startOf/endOf isoWeek', () => {
const ISOWEEK = 'isoWeek'
expect(dayjs().startOf(ISOWEEK).valueOf()).toBe(moment().startOf(ISOWEEK).valueOf())
Expand Down