Skip to content

Build your own AI office with Univer Office SDK. Bring editing, calculation, collaboration, and file processing into your product for people and AI agents. Built on an extensible open-source core.

fix: correct calendar date period boundaries (#7896)

wpxp123456996106a97c12
diff --git a/packages/core/src/shared/__tests__/date-kit.spec.ts b/packages/core/src/shared/__tests__/date-kit.spec.ts
index 5c75b3b914..426849fcce 100644
--- a/packages/core/src/shared/__tests__/date-kit.spec.ts
+++ b/packages/core/src/shared/__tests__/date-kit.spec.ts
@@ -44,6 +44,15 @@ describe('date-kit', () => {
expect(dateKit('2024-01-01').week()).toBeGreaterThanOrEqual(1);
});
+ it.each(['2026-03-08', '2026-11-01'])('counts calendar weeks across offset changes after %s', (start) => {
+ const sunday = dateKit(start);
+ const nextSunday = sunday.add(1, 'week');
+
+ expect(nextSunday.week()).toBe(sunday.week() + 1);
+ expect(sunday.week(nextSunday.week()).format('YYYY-MM-DD')).toBe(nextSunday.format('YYYY-MM-DD'));
+ expect(dateKit.utc(nextSunday.format('YYYY-MM-DD')).week()).toBe(nextSunday.week());
+ });
+
it('should support localized and advanced format tokens', () => {
const value = dateKit('2024-02-01 15:04:05');
expect(value.format('L')).toBe('02/01/2024');
diff --git a/packages/core/src/shared/date-kit.ts b/packages/core/src/shared/date-kit.ts
index 15fa133dcb..34663e77ca 100644
--- a/packages/core/src/shared/date-kit.ts
+++ b/packages/core/src/shared/date-kit.ts
@@ -433,9 +433,11 @@ function startOf(date: Date, unit: DateKitCoreUnit, isUTC: boolean) {
}
function getWeekOfYear(date: Date, isUTC: boolean) {
- const currentWeekStart = startOf(date, 'week', isUTC);
+ const current = getDateParts(startOf(date, 'week', isUTC), isUTC);
const yearStart = startOf(date, 'year', isUTC);
- const firstWeekStart = startOf(yearStart, 'week', isUTC);
+ const first = getDateParts(startOf(yearStart, 'week', isUTC), isUTC);
+ const currentWeekStart = createDateWithParts(current.year, current.month, current.day, 0, 0, 0, 0, true);
+ const firstWeekStart = createDateWithParts(first.year, first.month, first.day, 0, 0, 0, 0, true);
return Math.floor((currentWeekStart.getTime() - firstWeekStart.getTime()) / DAY / 7) + 1;
}
diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/highlight-cell-calculate-unit.spec.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/highlight-cell-calculate-unit.spec.ts
new file mode 100644
index 0000000000..428a8494c8
--- /dev/null
+++ b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/__tests__/highlight-cell-calculate-unit.spec.ts
@@ -0,0 +1,182 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import type { Workbook } from '@univerjs/core';
+import type { IConditionFormattingRule, ITimePeriodHighlightCell } from '../../type';
+import { BooleanNumber, CellValueType, excelDateTimeSerial } from '@univerjs/core';
+import { afterEach, describe, expect, it, vi } from 'vitest';
+import { CFRuleType, CFSubRuleType, CFTimePeriodOperator } from '../../../base/const';
+import { AddConditionalRuleMutation } from '../../../commands/mutations/add-conditional-rule.mutation';
+import { createTestBed } from './test.util';
+
+describe('HighlightCellCalculateUnit time periods', () => {
+ let testBed: ReturnType<typeof createTestBed> | undefined;
+
+ afterEach(() => {
+ testBed?.univer.dispose();
+ testBed = undefined;
+ vi.useRealTimers();
+ });
+
+ it.each([
+ {
+ operator: CFTimePeriodOperator.last7Days,
+ anchor: new Date(2026, 9, 16, 12),
+ start: Date.UTC(2026, 9, 10),
+ end: Date.UTC(2026, 9, 17),
+ },
+ {
+ operator: CFTimePeriodOperator.last7Days,
+ anchor: new Date(2026, 9, 16),
+ start: Date.UTC(2026, 9, 10),
+ end: Date.UTC(2026, 9, 17),
+ },
+ {
+ operator: CFTimePeriodOperator.last7Days,
+ anchor: new Date(2026, 9, 16, 23, 59, 59, 999),
+ start: Date.UTC(2026, 9, 10),
+ end: Date.UTC(2026, 9, 17),
+ },
+ {
+ operator: CFTimePeriodOperator.last7Days,
+ anchor: new Date(2026, 0, 3, 12),
+ start: Date.UTC(2025, 11, 28),
+ end: Date.UTC(2026, 0, 4),
+ },
+ {
+ operator: CFTimePeriodOperator.last7Days,
+ anchor: new Date(2024, 2, 3, 12),
+ start: Date.UTC(2024, 1, 26),
+ end: Date.UTC(2024, 2, 4),
+ },
+ {
+ operator: CFTimePeriodOperator.last7Days,
+ anchor: new Date(2026, 2, 9, 12),
+ start: Date.UTC(2026, 2, 3),
+ end: Date.UTC(2026, 2, 10),
+ },
+ {
+ operator: CFTimePeriodOperator.last7Days,
+ anchor: new Date(2026, 10, 2, 12),
+ start: Date.UTC(2026, 9, 27),
+ end: Date.UTC(2026, 10, 3),
+ },
+ {
+ operator: CFTimePeriodOperator.nextMonth,
+ anchor: new Date(2026, 1, 15, 12),
+ start: Date.UTC(2026, 2, 1),
+ end: Date.UTC(2026, 3, 1),
+ },
+ {
+ operator: CFTimePeriodOperator.lastMonth,
+ anchor: new Date(2026, 1, 15, 12),
+ start: Date.UTC(2026, 0, 1),
+ end: Date.UTC(2026, 1, 1),
+ },
+ {
+ operator: CFTimePeriodOperator.lastMonth,
+ anchor: new Date(2026, 8, 15, 12),
+ start: Date.UTC(2026, 7, 1),
+ end: Date.UTC(2026, 8, 1),
+ },
+ {
+ operator: CFTimePeriodOperator.nextMonth,
+ anchor: new Date(2026, 3, 30, 12),
+ start: Date.UTC(2026, 4, 1),
+ end: Date.UTC(2026, 5, 1),
+ },
+ {
+ operator: CFTimePeriodOperator.lastMonth,
+ anchor: new Date(2024, 2, 31, 12),
+ start: Date.UTC(2024, 1, 1),
+ end: Date.UTC(2024, 2, 1),
+ },
+ {
+ operator: CFTimePeriodOperator.nextMonth,
+ anchor: new Date(2024, 0, 31, 12),
+ start: Date.UTC(2024, 1, 1),
+ end: Date.UTC(2024, 2, 1),
+ },
+ {
+ operator: CFTimePeriodOperator.lastMonth,
+ anchor: new Date(2026, 2, 31, 12),
+ start: Date.UTC(2026, 1, 1),
+ end: Date.UTC(2026, 2, 1),
+ },
+ {
+ operator: CFTimePeriodOperator.nextMonth,
+ anchor: new Date(2026, 0, 31, 12),
+ start: Date.UTC(2026, 1, 1),
+ end: Date.UTC(2026, 2, 1),
+ },
+ {
+ operator: CFTimePeriodOperator.lastMonth,
+ anchor: new Date(2026, 0, 31, 12),
+ start: Date.UTC(2025, 11, 1),
+ end: Date.UTC(2026, 0, 1),
+ },
+ {
+ operator: CFTimePeriodOperator.nextMonth,
+ anchor: new Date(2026, 11, 31, 12),
+ start: Date.UTC(2027, 0, 1),
+ end: Date.UTC(2027, 1, 1),
+ },
+ ])('highlights the complete $operator for $anchor', ({ operator, anchor, start, end }) => {
+ vi.useFakeTimers({ toFake: ['Date'] });
+ vi.setSystemTime(anchor);
+ testBed = createTestBed();
+ testBed.getConditionalFormattingViewModel();
+ const { unitId, subUnitId } = testBed;
+
+ const worksheet = (testBed.workbook as Workbook).getSheetBySheetId(subUnitId)!;
+ const lastDay = new Date(end);
+ lastDay.setUTCDate(lastDay.getUTCDate() - 1);
+ const dates = [start - 1, start, lastDay.getTime(), end - 1, end];
+ for (const [row, timestamp] of dates.entries()) {
+ worksheet.getCellMatrix().setValue(row, 0, {
+ v: excelDateTimeSerial(new Date(timestamp)),
+ t: CellValueType.NUMBER,
+ });
+ }
+
+ const rule: IConditionFormattingRule<ITimePeriodHighlightCell> = {
+ cfId: 'relative-time-period',
+ ranges: [{ startRow: 0, endRow: dates.length - 1, startColumn: 0, endColumn: 0 }],
+ stopIfTrue: false,
+ rule: {
+ type: CFRuleType.highlightCell,
+ subType: CFSubRuleType.timePeriod,
+ operator,
+ style: { bl: BooleanNumber.TRUE },
+ },
+ };
+ testBed.commandService.syncExecuteCommand(AddConditionalRuleMutation.id, {
+ unitId,
+ subUnitId,
+ rule,
+ });
+
+ const service = testBed.getConditionalFormattingService();
+ const results = dates.map((_, row) => service.composeStyle(unitId, subUnitId, row, 0));
+ expect(results).toEqual([
+ { style: {} },
+ { style: { bl: BooleanNumber.TRUE } },
+ { style: { bl: BooleanNumber.TRUE } },
+ { style: { bl: BooleanNumber.TRUE } },
+ { style: {} },
+ ]);
+ });
+});
diff --git a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/highlight-cell-calculate-unit.ts b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/highlight-cell-calculate-unit.ts
index f733efd0d8..6611240fe3 100644
--- a/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/highlight-cell-calculate-unit.ts
+++ b/packages/sheets-conditional-formatting/src/models/calculate-unit-v2/highlight-cell-calculate-unit.ts
@@ -150,19 +150,21 @@ export class HighlightCellCalculateUnit extends BaseCalculateUnit<Nullable<IConf
const subRuleConfig = ruleConfig as ITimePeriodHighlightCell;
switch (subRuleConfig.operator) {
case CFTimePeriodOperator.last7Days: {
+ const today = dateKit().startOf('day');
return {
value: {
- start: dateKit().subtract(7, 'day').valueOf(),
- end: dateKit().valueOf(),
+ start: today.subtract(6, 'day').valueOf(),
+ end: today.endOf('day').valueOf(),
},
type: ruleConfig.subType,
};
}
case CFTimePeriodOperator.lastMonth: {
+ const month = dateKit().startOf('month').subtract(1, 'month');
return {
value: {
- start: dateKit().startOf('month').subtract(1, 'month').valueOf(),
- end: dateKit().endOf('month').subtract(1, 'month').valueOf(),
+ start: month.valueOf(),
+ end: month.endOf('month').valueOf(),
},
type: ruleConfig.subType,
};
@@ -177,10 +179,11 @@ export class HighlightCellCalculateUnit extends BaseCalculateUnit<Nullable<IConf
};
}
case CFTimePeriodOperator.nextMonth: {
+ const month = dateKit().startOf('month').add(1, 'month');
return {
value: {
- start: dateKit().startOf('month').add(1, 'month').valueOf(),
- end: dateKit().endOf('month').add(1, 'month').valueOf(),
+ start: month.valueOf(),
+ end: month.endOf('month').valueOf(),
},
type: ruleConfig.subType,
};
diff --git a/packages/sheets-table/src/models/filter-util/__tests__/date-filter-util.spec.ts b/packages/sheets-table/src/models/filter-util/__tests__/date-filter-util.spec.ts
new file mode 100644
index 0000000000..2d2ec8666b
--- /dev/null
+++ b/packages/sheets-table/src/models/filter-util/__tests__/date-filter-util.spec.ts
@@ -0,0 +1,33 @@
+/**
+ * Copyright 2023-present DreamNum Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+import { describe, expect, it } from 'vitest';
+import { lastWeek, nextWeek } from '../date-filter-util';
+
+describe('relative week date filters', () => {
+ it.each([
+ { matches: nextWeek, anchor: new Date(2026, 9, 26), start: new Date(2026, 10, 2) },
+ { matches: lastWeek, anchor: new Date(2026, 2, 9), start: new Date(2026, 2, 2) },
+ { matches: nextWeek, anchor: new Date(2026, 2, 2, 23, 30), start: new Date(2026, 2, 9) },
+ { matches: lastWeek, anchor: new Date(2026, 10, 2, 23, 30), start: new Date(2026, 9, 26) },
+ ])('matches all seven calendar dates for $anchor', ({ matches, anchor, start }) => {
+ for (let offset = -1; offset <= 7; offset++) {
+ const candidate = new Date(start);
+ candidate.setDate(candidate.getDate() + offset);
+ expect(matches(candidate, anchor)).toBe(offset >= 0 && offset < 7);
+ }
+ });
+});
diff --git a/packages/sheets-table/src/models/filter-util/date-filter-util.ts b/packages/sheets-table/src/models/filter-util/date-filter-util.ts
index 707c0a8dfb..700cd33c1b 100644
--- a/packages/sheets-table/src/models/filter-util/date-filter-util.ts
+++ b/packages/sheets-table/src/models/filter-util/date-filter-util.ts
@@ -212,8 +212,6 @@ const getWeekStart = (date: Date): Date => {
return weekStart;
};
-const perWeek = 7 * 24 * 60 * 60 * 1000;
-
/**
* The provided date is in the current week.
* @param {Date} date - The date to compare.
@@ -234,7 +232,8 @@ export const thisWeek = (date: Date, anchorTime: Date = new Date()): boolean =>
*/
export const nextWeek = (date: Date, anchorTime: Date = new Date()): boolean => {
const weekStart = getWeekStart(date);
- const anchorTimeNextWeekStart = new Date(getWeekStart(anchorTime).getTime() + perWeek);
+ const anchorTimeNextWeekStart = getWeekStart(anchorTime);
+ anchorTimeNextWeekStart.setDate(anchorTimeNextWeekStart.getDate() + 7);
return weekStart.toDateString() === anchorTimeNextWeekStart.toDateString();
};
@@ -246,7 +245,8 @@ export const nextWeek = (date: Date, anchorTime: Date = new Date()): boolean =>
*/
export const lastWeek = (date: Date, anchorTime: Date = new Date()): boolean => {
const weekStart = getWeekStart(date);
- const anchorTimeLastWeekStart = new Date(getWeekStart(anchorTime).getTime() - perWeek);
+ const anchorTimeLastWeekStart = getWeekStart(anchorTime);
+ anchorTimeLastWeekStart.setDate(anchorTimeLastWeekStart.getDate() - 7);
return weekStart.toDateString() === anchorTimeLastWeekStart.toDateString();
};