2020-07-28 08:52:14 +02:00
|
|
|
import moment from 'moment-timezone';
|
2020-07-29 04:04:45 +02:00
|
|
|
import {
|
|
|
|
addMinutes,
|
|
|
|
addHours,
|
|
|
|
startOfDay,
|
|
|
|
endOfHour,
|
|
|
|
endOfDay,
|
|
|
|
startOfHour,
|
|
|
|
addDays,
|
|
|
|
subDays,
|
|
|
|
subHours,
|
|
|
|
differenceInHours,
|
|
|
|
differenceInDays,
|
|
|
|
} from 'date-fns';
|
2020-07-28 08:52:14 +02:00
|
|
|
|
|
|
|
export function getTimezone() {
|
2020-07-29 04:04:45 +02:00
|
|
|
return moment.tz.guess();
|
|
|
|
}
|
|
|
|
|
|
|
|
export function getTimezonAbbr() {
|
|
|
|
return moment.tz.zone(getTimezone()).abbr(new Date().getTimezoneOffset());
|
2020-07-28 08:52:14 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
export function getLocalTime(t) {
|
|
|
|
return addMinutes(new Date(t), new Date().getTimezoneOffset());
|
|
|
|
}
|
2020-07-28 10:17:45 +02:00
|
|
|
|
|
|
|
export function getDateRange(value) {
|
|
|
|
const now = new Date();
|
2020-07-29 04:04:45 +02:00
|
|
|
const hour = endOfHour(now);
|
|
|
|
const day = endOfDay(now);
|
2020-07-28 10:17:45 +02:00
|
|
|
|
2020-07-30 08:25:52 +02:00
|
|
|
const { num, unit } = value.match(/^(?<num>[0-9]+)(?<unit>hour|day)$/).groups;
|
|
|
|
|
|
|
|
switch (unit) {
|
|
|
|
case 'day':
|
2020-07-28 10:17:45 +02:00
|
|
|
return {
|
2020-07-30 08:25:52 +02:00
|
|
|
startDate: subDays(day, num),
|
2020-07-29 04:04:45 +02:00
|
|
|
endDate: day,
|
2020-07-30 08:25:52 +02:00
|
|
|
unit,
|
2020-07-28 10:17:45 +02:00
|
|
|
};
|
2020-07-30 08:25:52 +02:00
|
|
|
case 'hour':
|
2020-07-28 10:17:45 +02:00
|
|
|
return {
|
2020-07-30 08:25:52 +02:00
|
|
|
startDate: subHours(hour, num),
|
2020-07-29 04:04:45 +02:00
|
|
|
endDate: hour,
|
2020-07-30 08:25:52 +02:00
|
|
|
unit,
|
2020-07-28 10:17:45 +02:00
|
|
|
};
|
|
|
|
}
|
|
|
|
}
|
2020-07-29 04:04:45 +02:00
|
|
|
|
|
|
|
const dateFuncs = {
|
|
|
|
hour: [differenceInHours, addHours, startOfHour],
|
|
|
|
day: [differenceInDays, addDays, startOfDay],
|
|
|
|
};
|
|
|
|
|
|
|
|
export function getDateArray(data, startDate, endDate, unit) {
|
|
|
|
const arr = [];
|
|
|
|
const [diff, add, normalize] = dateFuncs[unit];
|
|
|
|
const n = diff(endDate, startDate);
|
|
|
|
|
|
|
|
function findData(t) {
|
|
|
|
return data.find(e => getLocalTime(e.t).getTime() === normalize(t).getTime())?.y || 0;
|
|
|
|
}
|
|
|
|
|
|
|
|
for (let i = 0; i < n; i++) {
|
|
|
|
const t = add(startDate, i + 1);
|
|
|
|
const y = findData(t);
|
|
|
|
|
|
|
|
arr.push({ t, y });
|
|
|
|
}
|
|
|
|
|
|
|
|
return arr;
|
|
|
|
}
|