diff --git a/package.json b/package.json index be0d68cab..adf64da19 100644 --- a/package.json +++ b/package.json @@ -75,6 +75,7 @@ "luxon": "3.x", "mockdate": "^3.0.2", "moment": "^2.24.0", + "moment-timezone": "^0.5.45", "np": "^10.0.2", "prettier": "^3.1.0", "rc-test": "^7.0.9", diff --git a/src/generate/dayjs.ts b/src/generate/dayjs.ts index aae56610b..91291ce30 100644 --- a/src/generate/dayjs.ts +++ b/src/generate/dayjs.ts @@ -107,7 +107,14 @@ const parseNoMatchNotice = () => { const generateConfig: GenerateConfig = { // get - getNow: () => dayjs(), + getNow: () => { + const now = dayjs(); + // https://github.com/ant-design/ant-design/discussions/50934 + if (typeof now.tz === 'function') { + return now.tz(); // use default timezone + } + return now; + }, getFixedDate: (string) => dayjs(string, ['YYYY-M-DD', 'YYYY-MM-DD']), getEndDate: (date) => date.endOf('month'), getWeekDay: (date) => { diff --git a/tests/generateWithTZ.spec.tsx b/tests/generateWithTZ.spec.tsx new file mode 100644 index 000000000..d53b344d8 --- /dev/null +++ b/tests/generateWithTZ.spec.tsx @@ -0,0 +1,43 @@ +import MockDate from 'mockdate'; +import dayjsGenerateConfig from '../src/generate/dayjs'; + +import dayjs from 'dayjs'; +import utc from 'dayjs/plugin/utc'; +import timezone from 'dayjs/plugin/timezone'; +import moment from 'moment-timezone'; + +dayjs.extend(utc); +dayjs.extend(timezone); + +const CN = 'Asia/Shanghai'; +const JP = 'Asia/Tokyo'; + +beforeEach(() => { + MockDate.set(new Date()); + dayjs.tz.setDefault(CN); + moment.tz.setDefault(CN); +}); + +afterEach(() => { + dayjs.tz.setDefault(); + moment.tz.setDefault(); + MockDate.reset(); +}); + +describe('dayjs: getNow', () => { + it('normal', () => { + const D_now = dayjsGenerateConfig.getNow(); + const M_now = moment(); + + expect(D_now.format()).toEqual(M_now.format()); + }); + + it('should work normally in timezone', async () => { + dayjs.tz.setDefault(JP); + const D_now = dayjsGenerateConfig.getNow(); + const M_now = moment().tz(JP); + + expect(D_now.format()).toEqual(M_now.format()); + expect(D_now.get('hour') - D_now.utc().get('hour')).toEqual(9); + }); +}); diff --git a/tsconfig.json b/tsconfig.json index 5e7976cfb..06c770c29 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -19,6 +19,7 @@ "src/**/*.tsx", "docs/examples/*.tsx", "tests/**/*.ts", - "tests/**/*.tsx" + "tests/**/*.tsx", + "typings.d.ts" ] } diff --git a/typings.d.ts b/typings.d.ts new file mode 100644 index 000000000..91381c62b --- /dev/null +++ b/typings.d.ts @@ -0,0 +1,3 @@ +import 'dayjs/plugin/timezone'; + +export {};