From 3bdbcb2951219112bbbe8209aecad4f06179555f Mon Sep 17 00:00:00 2001 From: Stefano Pigozzi <256895@studenti.unimore.it> Date: Fri, 7 May 2021 04:47:48 +0200 Subject: [PATCH] =?UTF-8?q?=E2=9C=A8=20Create=20convertToLocalISODate=20fu?= =?UTF-8?q?nction?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/utils/convertToLocalISODate.js | 30 +++++++++++++++++++ 1 file changed, 30 insertions(+) create mode 100644 code/frontend/src/utils/convertToLocalISODate.js diff --git a/code/frontend/src/utils/convertToLocalISODate.js b/code/frontend/src/utils/convertToLocalISODate.js new file mode 100644 index 0000000..bfc583a --- /dev/null +++ b/code/frontend/src/utils/convertToLocalISODate.js @@ -0,0 +1,30 @@ +// Wow, JS, davvero? +// Davvero tutte le date.toISOString() sono considerate UTC? +// Wow. + +/** + * Convert a {@link Date} object to a timezone aware ISO String, using the user's local timezone. + * + * @param date + * @returns {string} + */ +export default function convertToLocalISODate(date) { + if(date.toString() === "Invalid Date") { + throw new Error("Received an Invalid Date as parameter.") + } + + // Create a timezone naive ISO string + const naive = date.toISOString() + + // Find the local timezone + const tz = - new Date().getTimezoneOffset() + + // Convert the timezone to hours + const tzHours = Math.abs(Math.floor(tz / 60)).toString().padStart(2, "0") + + // Find the minutes + const tzMinutes = (tz % 60).toString().padStart(2, "0") + + // Replace the naive part with the aware part + return naive.replace("Z", `${tz < 0 ? "-" : "+"}${tzHours}${tzMinutes}`) +} \ No newline at end of file