Skip to content

Commit d3fda29

Browse files
fix #383 (#515)
* fix #383 * add tests about datetime
1 parent 5f88ac0 commit d3fda29

File tree

2 files changed

+29
-2
lines changed

2 files changed

+29
-2
lines changed

packages/core-base/src/datetime.ts

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -302,10 +302,18 @@ export function parseDateTimeArgs(
302302
if (isString(arg1)) {
303303
// Only allow ISO strings - other date formats are often supported,
304304
// but may cause different results in different browsers.
305-
if (!/\d{4}-\d{2}-\d{2}(T.*)?/.test(arg1)) {
305+
const matches = arg1.match(/(\d{4}-\d{2}-\d{2})(T|\s)?(.*)/)
306+
if (!matches) {
306307
throw createCoreError(CoreErrorCodes.INVALID_ISO_DATE_ARGUMENT)
307308
}
308-
value = new Date(arg1)
309+
// Some browsers can not parse the iso datetime separated by space,
310+
// this is a compromise solution by replace the 'T'/' ' with 'T'
311+
const dateTime = matches[3]
312+
? matches[3].trim().startsWith('T')
313+
? `${matches[1].trim()}${matches[3].trim()}`
314+
: `${matches[1].trim()}T${matches[3].trim()}`
315+
: matches[1].trim()
316+
value = new Date(dateTime)
309317

310318
try {
311319
// This will fail if the date is not valid

packages/core-base/test/datetime.test.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -64,6 +64,16 @@ const datetimeFormats: DateTimeFormats<MyDateTimeSchema, 'en-US' | 'ja-JP'> = {
6464
}
6565

6666
const dt = new Date(Date.UTC(2012, 11, 20, 3, 0, 0))
67+
const dts = [
68+
'2012-12-20 03:00',
69+
'2012-12-20 03:00',
70+
'2012-12-20 03:00:00',
71+
'2012-12-20 03:00:00',
72+
'2012-12-20T03:00',
73+
'2012-12-20 T03:00',
74+
'2012-12-20T03:00:00',
75+
'2012-12-20 T03:00:00'
76+
]
6777

6878
beforeEach(() => {
6979
registerMessageCompiler(compileToFunction)
@@ -112,6 +122,9 @@ test('key argument', () => {
112122
})
113123

114124
expect(datetime(ctx, dt, 'short')).toEqual('12/19/2012, 10:00 PM')
125+
dts.forEach(dt => {
126+
expect(datetime(ctx, dt, 'short')).toEqual('12/19/2012, 10:00 PM')
127+
})
115128
})
116129

117130
test('locale argument', () => {
@@ -127,6 +140,9 @@ test('locale argument', () => {
127140
})
128141

129142
expect(datetime(ctx, dt, 'short', 'ja-JP')).toEqual('2012/12/20 12:00')
143+
dts.forEach(dt => {
144+
expect(datetime(ctx, dt, 'short', 'ja-JP')).toEqual('2012/12/20 12:00')
145+
})
130146
})
131147

132148
test('with object argument', () => {
@@ -211,6 +227,9 @@ test(`context fallbackWarn 'false' option`, () => {
211227
})
212228

213229
expect(datetime(ctx, dt, 'long')).toEqual('2012/12/20 12:00:00')
230+
dts.forEach(dt => {
231+
expect(datetime(ctx, dt, 'long')).toEqual('2012/12/20 12:00:00')
232+
})
214233
expect(mockWarn).not.toHaveBeenCalled()
215234
})
216235

0 commit comments

Comments
 (0)