Skip to content

Commit 5e0818c

Browse files
committed
Only infer strings as timestamps if they are within 2 years of the current date
1 parent 4179cf2 commit 5e0818c

File tree

2 files changed

+44
-18
lines changed

2 files changed

+44
-18
lines changed

src/formats/timestamp.ts

+35-12
Original file line numberDiff line numberDiff line change
@@ -7,26 +7,49 @@ const timestampSecondsSinceEpoch = /^\d{10}$/;
77
const timestampMsSinceEpoch = /^\d{13}$/;
88
const timestampNanoSinceEpoch = /^\d{19}$/;
99

10+
// If the msSinceEpoch is within 2 years of the current time, then inRangeOfNow will be true
11+
function inRangeOfNow(msSinceEpoch: number): boolean {
12+
const now = new Date().getTime();
13+
const acceptableRange = 2 * 365 * 24 * 60 * 60 * 1000;
14+
15+
const lowerBound = msSinceEpoch - acceptableRange;
16+
const upperBound = msSinceEpoch + acceptableRange;
17+
18+
return now >= lowerBound && now <= upperBound;
19+
}
20+
1021
export function inferTimestamp(value: string): JSONTimestampFormat | undefined {
1122
if (timestampSecondsSinceEpoch.test(value)) {
12-
return {
13-
name: "timestamp",
14-
variant: "secondsSinceEpoch",
15-
};
23+
const seconds = parseInt(value);
24+
25+
if (inRangeOfNow(seconds * 1000)) {
26+
return {
27+
name: "timestamp",
28+
variant: "secondsSinceEpoch",
29+
};
30+
}
1631
}
1732

1833
if (timestampMsSinceEpoch.test(value)) {
19-
return {
20-
name: "timestamp",
21-
variant: "millisecondsSinceEpoch",
22-
};
34+
const milliseconds = parseInt(value);
35+
36+
if (inRangeOfNow(milliseconds)) {
37+
return {
38+
name: "timestamp",
39+
variant: "millisecondsSinceEpoch",
40+
};
41+
}
2342
}
2443

2544
if (timestampNanoSinceEpoch.test(value)) {
26-
return {
27-
name: "timestamp",
28-
variant: "nanosecondsSinceEpoch",
29-
};
45+
const nanoseconds = parseInt(value);
46+
47+
if (inRangeOfNow(nanoseconds / 1000000)) {
48+
return {
49+
name: "timestamp",
50+
variant: "nanosecondsSinceEpoch",
51+
};
52+
}
3053
}
3154

3255
return undefined;

tests/stringFormats.test.ts

+9-6
Original file line numberDiff line numberDiff line change
@@ -813,10 +813,13 @@ describe("credit cards", () => {
813813
});
814814

815815
describe("without format", () => {
816-
test.each(["46"])("%p should be inferred as having no format", (value) => {
817-
expect(inferType(value)).toEqual({
818-
name: "string",
819-
value,
820-
});
821-
});
816+
test.each(["46", "2244994945", "1212092628029698048"])(
817+
"%p should be inferred as having no format",
818+
(value) => {
819+
expect(inferType(value)).toEqual({
820+
name: "string",
821+
value,
822+
});
823+
},
824+
);
822825
});

0 commit comments

Comments
 (0)