Skip to content

Commit df3e060

Browse files
authored
feat(getNow): improve the current time acquisition method (#878)
1 parent 7689208 commit df3e060

File tree

5 files changed

+57
-2
lines changed

5 files changed

+57
-2
lines changed

package.json

+1
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@
7575
"luxon": "3.x",
7676
"mockdate": "^3.0.2",
7777
"moment": "^2.24.0",
78+
"moment-timezone": "^0.5.45",
7879
"np": "^10.0.2",
7980
"prettier": "^3.1.0",
8081
"rc-test": "^7.0.9",

src/generate/dayjs.ts

+8-1
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,14 @@ const parseNoMatchNotice = () => {
107107

108108
const generateConfig: GenerateConfig<Dayjs> = {
109109
// get
110-
getNow: () => dayjs(),
110+
getNow: () => {
111+
const now = dayjs();
112+
// https://github.com/ant-design/ant-design/discussions/50934
113+
if (typeof now.tz === 'function') {
114+
return now.tz(); // use default timezone
115+
}
116+
return now;
117+
},
111118
getFixedDate: (string) => dayjs(string, ['YYYY-M-DD', 'YYYY-MM-DD']),
112119
getEndDate: (date) => date.endOf('month'),
113120
getWeekDay: (date) => {

tests/generateWithTZ.spec.tsx

+43
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
import MockDate from 'mockdate';
2+
import dayjsGenerateConfig from '../src/generate/dayjs';
3+
4+
import dayjs from 'dayjs';
5+
import utc from 'dayjs/plugin/utc';
6+
import timezone from 'dayjs/plugin/timezone';
7+
import moment from 'moment-timezone';
8+
9+
dayjs.extend(utc);
10+
dayjs.extend(timezone);
11+
12+
const CN = 'Asia/Shanghai';
13+
const JP = 'Asia/Tokyo';
14+
15+
beforeEach(() => {
16+
MockDate.set(new Date());
17+
dayjs.tz.setDefault(CN);
18+
moment.tz.setDefault(CN);
19+
});
20+
21+
afterEach(() => {
22+
dayjs.tz.setDefault();
23+
moment.tz.setDefault();
24+
MockDate.reset();
25+
});
26+
27+
describe('dayjs: getNow', () => {
28+
it('normal', () => {
29+
const D_now = dayjsGenerateConfig.getNow();
30+
const M_now = moment();
31+
32+
expect(D_now.format()).toEqual(M_now.format());
33+
});
34+
35+
it('should work normally in timezone', async () => {
36+
dayjs.tz.setDefault(JP);
37+
const D_now = dayjsGenerateConfig.getNow();
38+
const M_now = moment().tz(JP);
39+
40+
expect(D_now.format()).toEqual(M_now.format());
41+
expect(D_now.get('hour') - D_now.utc().get('hour')).toEqual(9);
42+
});
43+
});

tsconfig.json

+2-1
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
"src/**/*.tsx",
2020
"docs/examples/*.tsx",
2121
"tests/**/*.ts",
22-
"tests/**/*.tsx"
22+
"tests/**/*.tsx",
23+
"typings.d.ts"
2324
]
2425
}

typings.d.ts

+3
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
import 'dayjs/plugin/timezone';
2+
3+
export {};

0 commit comments

Comments
 (0)