2021-06-21 13:38:43 +02:00

94 lines
1.9 KiB
JavaScript

/**
* Some utils for manipulating dates
*
* **WARNING** experimental
*/
/**
* 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) => {
if (null === date) {
return null;
}
return [
date.getFullYear(),
(date.getMonth() + 1).toString().padStart(2, '0'),
date.getDate().toString().padStart(2, '0')
].join('-');
};
/**
* Return a date object from iso string formatted as YYYY-mm-dd
*
* **Experimental**
*/
const ISOToDate = (str) => {
let
[year, month, day] = str.split('-');
return new Date(year, month-1, day);
}
/**
* Return a date object from iso string formatted as YYYY-mm-dd:HH:MM:ss+01:00
*
*/
const ISOToDatetime = (str) => {
if (null === str) {
return null;
}
let
[cal, times] = str.split('T'),
[year, month, date] = cal.split('-'),
[time, timezone] = cal.split(times.charAt(9)),
[hours, minutes, seconds] = cal.split(':')
;
return new Date(year, month-1, date, hours, minutes, seconds);
}
/**
* 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;
return x;
};
export {
dateToISO,
ISOToDate,
ISOToDatetime,
datetimeToISO
};