Skip to content

Commit

Permalink
feat(getNow): improve the current time acquisition method (#878)
Browse files Browse the repository at this point in the history
  • Loading branch information
Wxh16144 committed Sep 24, 2024
1 parent 7689208 commit df3e060
Show file tree
Hide file tree
Showing 5 changed files with 57 additions and 2 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
9 changes: 8 additions & 1 deletion src/generate/dayjs.ts
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,14 @@ const parseNoMatchNotice = () => {

const generateConfig: GenerateConfig<Dayjs> = {
// 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) => {
Expand Down
43 changes: 43 additions & 0 deletions tests/generateWithTZ.spec.tsx
Original file line number Diff line number Diff line change
@@ -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);
});
});
3 changes: 2 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"src/**/*.tsx",
"docs/examples/*.tsx",
"tests/**/*.ts",
"tests/**/*.tsx"
"tests/**/*.tsx",
"typings.d.ts"
]
}
3 changes: 3 additions & 0 deletions typings.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import 'dayjs/plugin/timezone';

export {};

0 comments on commit df3e060

Please sign in to comment.