From c89ad9b03883085c35f88e05bcec25ecdacef3e7 Mon Sep 17 00:00:00 2001 From: Jesse Tan Date: Mon, 6 Apr 2020 06:19:14 +0200 Subject: [PATCH] TimeSrv: Try to parse 8 and 15 digit numbers as timestamps if parsing as date fails (#21694) * Try to parse 8 and 15 digit numbers as timestamps if parsing as date fails Fixes #19738 * Add tests --- .../dashboard/services/TimeSrv.test.ts | 32 +++++++++++++++++++ .../features/dashboard/services/TimeSrv.ts | 13 +++++--- 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/public/app/features/dashboard/services/TimeSrv.test.ts b/public/app/features/dashboard/services/TimeSrv.test.ts index d9e5adfebaf..04786c33b43 100644 --- a/public/app/features/dashboard/services/TimeSrv.test.ts +++ b/public/app/features/dashboard/services/TimeSrv.test.ts @@ -135,6 +135,38 @@ describe('timeSrv', () => { expect(time.to.valueOf()).toEqual(1410337665699); }); + it('should handle epochs that look like formatted date without time', () => { + location = { + search: jest.fn(() => ({ + from: '20149999', + to: '20159999', + })), + }; + + timeSrv = new TimeSrv(rootScope as any, jest.fn() as any, location as any, timer, new ContextSrvStub() as any); + + timeSrv.init(_dashboard); + const time = timeSrv.timeRange(); + expect(time.from.valueOf()).toEqual(20149999); + expect(time.to.valueOf()).toEqual(20159999); + }); + + it('should handle epochs that look like formatted date', () => { + location = { + search: jest.fn(() => ({ + from: '201499991234567', + to: '201599991234567', + })), + }; + + timeSrv = new TimeSrv(rootScope as any, jest.fn() as any, location as any, timer, new ContextSrvStub() as any); + + timeSrv.init(_dashboard); + const time = timeSrv.timeRange(); + expect(time.from.valueOf()).toEqual(201499991234567); + expect(time.to.valueOf()).toEqual(201599991234567); + }); + it('should handle bad dates', () => { location = { search: jest.fn(() => ({ diff --git a/public/app/features/dashboard/services/TimeSrv.ts b/public/app/features/dashboard/services/TimeSrv.ts index 7d2e522fece..dbc5b176941 100644 --- a/public/app/features/dashboard/services/TimeSrv.ts +++ b/public/app/features/dashboard/services/TimeSrv.ts @@ -102,10 +102,15 @@ export class TimeSrv { return value; } if (value.length === 8) { - return toUtc(value, 'YYYYMMDD'); - } - if (value.length === 15) { - return toUtc(value, 'YYYYMMDDTHHmmss'); + const utcValue = toUtc(value, 'YYYYMMDD'); + if (utcValue.isValid()) { + return utcValue; + } + } else if (value.length === 15) { + const utcValue = toUtc(value, 'YYYYMMDDTHHmmss'); + if (utcValue.isValid()) { + return utcValue; + } } if (!isNaN(value)) {