Skip to content

Commit 3a8dd13

Browse files
authored
feat(utils): allow dateparts without day specified (#16)
1 parent 16ed8de commit 3a8dd13

File tree

2 files changed

+19
-8
lines changed

2 files changed

+19
-8
lines changed

src/utils.ts

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -85,16 +85,20 @@ export function DateZFromDateParts(d: DateParts, opts: DateParseOpts = DefaultOp
8585
throw new Error('Malformed DateParts: Multiple DateParts possibilities found')
8686
}
8787

88+
// choose the first dateparts in the list.
89+
// TODO this is opinionated behavior and may need to adapt.
8890
const best = p[0]
89-
if (best.length != 3) {
90-
throw new Error('Malformed DateParts: Must have exactly year, month, and day')
91-
}
92-
93-
const yr = best[0]
94-
const moIdx = best[1] - 1
95-
const day = best[2]
9691

97-
return new Date(Date.UTC(yr, moIdx, day))
92+
switch (best.length) {
93+
case 1:
94+
return new Date(Date.UTC(best[0], 0, 1))
95+
case 2:
96+
return new Date(Date.UTC(best[0], best[1] - 1, 1))
97+
case 3:
98+
return new Date(Date.UTC(best[0], best[1] - 1, best[2]))
99+
default:
100+
throw new Error('Malformed DateParts: Must have 1, 2, or 3 parts')
101+
}
98102
}
99103

100104
/**

test/unit/utils.test.ts

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,13 @@ test('date utilities: DateParts only', async (t) => {
1919
t.is(result, '2021-01-21T00:00:00.000Z')
2020
})
2121

22+
test('date utilities: DateParts only with only year and month', async (t) => {
23+
const result = U.DatemorphISOString({
24+
'date-parts': [CONSISTENT_DATE['date-parts'][0].slice(0, 1)],
25+
})
26+
t.is(result, '2021-01-01T00:00:00.000Z')
27+
})
28+
2229
test('date utilities: Inconsistent date, strict', async (t) => {
2330
t.throws(() => {
2431
U.DatemorphISOString(INCONSISTENT_DATE)

0 commit comments

Comments
 (0)