add utility for date

This commit is contained in:
Julien Fastré 2021-06-04 21:23:51 +02:00
parent 502a629dc8
commit 48e5809008

View File

@ -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
};