From fabe44293e5f5f343176ea770a45fff312f82bfe Mon Sep 17 00:00:00 2001 From: Matthias Date: Mon, 10 Apr 2023 17:40:56 +0200 Subject: [PATCH] Add tests for timeformat "parseDate" --- src/shared/formatters/timeformat.ts | 6 ++++-- tests/unit/timeformat.spec.ts | 12 ++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/src/shared/formatters/timeformat.ts b/src/shared/formatters/timeformat.ts index d55bf008..f52d2362 100644 --- a/src/shared/formatters/timeformat.ts +++ b/src/shared/formatters/timeformat.ts @@ -1,10 +1,12 @@ import { parse, toDate } from 'date-fns'; -import { format, utcToZonedTime } from 'date-fns-tz'; +import { format, utcToZonedTime, zonedTimeToUtc } from 'date-fns-tz'; import humanizeDuration from 'humanize-duration'; import { isUndefined } from './numberformat'; +/** Parse date from string, returns date in UTC! */ export function dateFromString(datestring: string, format: string): Date { - return parse(datestring, format, 0); + const localTime = parse(datestring, format, 0); + return zonedTimeToUtc(localTime, 'UTC'); } let locTimeZone = 'UTC'; diff --git a/tests/unit/timeformat.spec.ts b/tests/unit/timeformat.spec.ts index 62d45188..6f266f93 100644 --- a/tests/unit/timeformat.spec.ts +++ b/tests/unit/timeformat.spec.ts @@ -6,6 +6,7 @@ import { timestampToDateString, dateStringToTimeRange, timestampHour, + dateFromString, } from '@/shared/formatters'; const { getTimeZone } = exportForTesting; @@ -58,4 +59,15 @@ describe('timeformatter.ts', () => { setTimezone('CET'); expect(timestampHour(1651057500000)).toEqual(13); }); + it('dateFromString converts correctly', () => { + expect(dateFromString('2022-04-04', 'yyyy-MM-dd')).toEqual( + new Date('2022-04-04T00:00:00.000Z'), + ); + expect(dateFromString('2023-02-08', 'yyyy-MM-dd')).toEqual( + new Date('2023-02-08T00:00:00.000Z'), + ); + expect(dateFromString('2022-12-31', 'yyyy-MM-dd')).toEqual( + new Date('2022-12-31T00:00:00.000Z'), + ); + }); });