From 58142d3157c71ac471781ee476c399b4efd2ec57 Mon Sep 17 00:00:00 2001 From: Mastermindzh Date: Thu, 15 Jul 2021 10:57:14 +0200 Subject: [PATCH] added getCustomIsoString --- typescript/datetime/getCustomIsoString.ts | 28 +++++++++++++++++++++++ 1 file changed, 28 insertions(+) create mode 100644 typescript/datetime/getCustomIsoString.ts diff --git a/typescript/datetime/getCustomIsoString.ts b/typescript/datetime/getCustomIsoString.ts new file mode 100644 index 0000000..22744b4 --- /dev/null +++ b/typescript/datetime/getCustomIsoString.ts @@ -0,0 +1,28 @@ +/** + * Given a JS date returns a valid ISO date string with offset + * + * const myDate = new Date(); + * console.log(getCustomIsoString(myDate)); + * > 2021-07-07T13:35:18+02:00 + * + */ +const getCustomIsoString = (date: Date) => { + /** + * If the month is smaller than 10, add a 0 in front of the string + */ + const pad = (num: number): string => { + const norm = Math.floor(Math.abs(num)); + return (norm < 10 ? "0" : "") + norm.toString(); + }; + + const timeZoneOffset = -date.getTimezoneOffset(); + const timeZoneDifference = timeZoneOffset >= 0 ? "+" : "-"; + + return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad( + date.getDate() + )}T${pad(date.getHours())}:${pad(date.getMinutes())}:${pad( + date.getSeconds() + )}${timeZoneDifference}${pad(timeZoneOffset / 60)}:${pad( + timeZoneOffset % 60 + )}`; +};