diff --git a/src/date.ts b/src/date.ts index f3dae43..74cd73c 100644 --- a/src/date.ts +++ b/src/date.ts @@ -166,7 +166,7 @@ export function timestamp(t?: number | string): number | Date { // Convert timestamp to Date // Timestamp(timestampValue) let v = typeof t === 'string' ? Number(t) : t; - if (String(v).length === 10) { + if (String(v).length === 10 || (v < 0 && Number.isInteger(v) && String(-v).length === 10)) { v *= 1000; } return new Date(v); diff --git a/test/date.test.ts b/test/date.test.ts index c6f348b..cebd5be 100644 --- a/test/date.test.ts +++ b/test/date.test.ts @@ -250,6 +250,25 @@ describe('test/date.test.ts', () => { assert.equal((utility.timestamp('1385091596') as Date).getTime(), 1385091596000); assert.equal((utility.timestamp('1385091596000') as Date).getTime(), 1385091596000); }); + + it('should parse negative seconds while preserving existing unit inference', () => { + const cases: Array<[number | string, number]> = [ + [ -1385091596, -1385091596000 ], + [ '-1385091596', -1385091596000 ], + [ 1385091596000, 1385091596000 ], + [ -1385091596000, -1385091596000 ], + [ 1385091596, 1385091596000 ], + [ -138509159, -138509159000 ], + [ '-138509159', -138509159000 ], + [ -12345.6789, -12345 ], + [ '-12345.6789', -12345 ], + [ 12345.6789, 12345678 ], + [ '12345.6789', 12345678 ], + ]; + for (const [ input, expected ] of cases) { + assert.equal((utility.timestamp(input) as Date).getTime(), expected, String(input)); + } + }); }); describe('dateToUnixTimestamp()', () => {