From 48e58090087d527336936f8a15a62f88b8ec15a9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Julien=20Fastr=C3=A9?= Date: Fri, 4 Jun 2021 21:23:51 +0200 Subject: [PATCH] add utility for date --- .../Resources/public/js/date.js | 64 +++++++++++++++++++ 1 file changed, 64 insertions(+) create mode 100644 src/Bundle/ChillMainBundle/Resources/public/js/date.js diff --git a/src/Bundle/ChillMainBundle/Resources/public/js/date.js b/src/Bundle/ChillMainBundle/Resources/public/js/date.js new file mode 100644 index 000000000..35499e1aa --- /dev/null +++ b/src/Bundle/ChillMainBundle/Resources/public/js/date.js @@ -0,0 +1,64 @@ +/** + * Some utils for manipulating dates + */ + +/** + * Return the date to local ISO date, like YYYY-mm-dd + * + * The date is valid for the same timezone as the date's locale + * + * Do not take time into account + */ +const dateToISO = (date) => { + return [ + this.$store.state.startDate.getFullYear(), + (this.$store.state.startDate.getMonth() + 1).toString().padStart(2, '0'), + this.$store.state.startDate.getDate().toString().padStart(2, '0') + ].join('-'); +}; + +/** + * Return a date object from iso string formatted as YYYY-mm-dd + */ +const ISOToDate = (str) => { + let + [year, month, day] = str.split('-'); + + return new Date(year, month-1, day); +} + +/** + * Convert a date to ISO8601, valid for usage in api + */ +const datetimeToISO = (date) => { + let cal, time, offset; + cal = [ + date.getFullYear(), + (date.getMonth() + 1).toString().padStart(2, '0'), + date.getDate().toString().padStart(2, '0') + ].join('-'); + + time = [ + date.getHours().toString().padStart(2, '0'), + date.getMinutes().toString().padStart(2, '0'), + date.getSeconds().toString().padStart(2, '0') + ].join(':'); + + offset = [ + date.getTimezoneOffset() <= 0 ? '+' : '-', + Math.abs(Math.floor(date.getTimezoneOffset() / 60)).toString().padStart(2, '0'), + ':', + Math.abs(date.getTimezoneOffset() % 60).toString().padStart(2, '0'), + ].join(''); + + let x = cal + 'T' + time + offset; + console.log('return date', x); + + return x; +}; + +export { + dateToISO, + ISOToDate, + datetimeToISO +};