Skip to content

Commit 3fe55ef

Browse files
fix(date_range): snap weekly start to anchor before generating dates
For W/W-MON etc. frequencies, genFromStart and genBetween now call snapToAnchor() to advance the cursor to the first occurrence of the anchor weekday on or after the provided start date, matching pandas behaviour where date_range('2024-01-01', periods=4, freq='W') returns four Sundays rather than a Monday followed by three Sundays. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 0aabe21 commit 3fe55ef

1 file changed

Lines changed: 16 additions & 2 deletions

File tree

src/stats/date_range.ts

Lines changed: 16 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -413,10 +413,24 @@ function retreatDate(d: Date, pf: ParsedFreq): Date {
413413

414414
// ─── generation helpers ────────────────────────────────────────────────────────
415415

416+
/**
417+
* For anchor-based frequencies (e.g. "W"), snap `d` forward to the first
418+
* occurrence of the anchor day on or after `d`. For all other frequencies
419+
* the date is returned unchanged.
420+
*/
421+
function snapToAnchor(d: Date, pf: ParsedFreq): Date {
422+
if (pf.unit === "W") {
423+
const dow = d.getUTCDay();
424+
const daysUntil = (pf.anchor - dow + 7) % 7;
425+
return daysUntil === 0 ? d : new Date(d.getTime() + daysUntil * MS_DAY);
426+
}
427+
return d;
428+
}
429+
416430
/** Generate `count` dates starting from `start`, advancing by `pf` each step. */
417431
function genFromStart(start: Date, count: number, pf: ParsedFreq): Date[] {
418432
const out: Date[] = [];
419-
let cur = start;
433+
let cur = snapToAnchor(start, pf);
420434
for (let i = 0; i < count; i++) {
421435
out.push(cur);
422436
cur = advanceDate(cur, pf);
@@ -430,7 +444,7 @@ function genFromStart(start: Date, count: number, pf: ParsedFreq): Date[] {
430444
*/
431445
function genBetween(start: Date, end: Date, pf: ParsedFreq): Date[] {
432446
const out: Date[] = [];
433-
let cur = start;
447+
let cur = snapToAnchor(start, pf);
434448
while (cur.getTime() <= end.getTime()) {
435449
out.push(cur);
436450
const next = advanceDate(cur, pf);

0 commit comments

Comments
 (0)