Fixed date range calculations.

This commit is contained in:
Mike Cao 2020-07-30 22:40:16 -07:00
parent 9f112c8cc9
commit 38abd673f3
8 changed files with 55 additions and 21 deletions

View file

@ -7,10 +7,14 @@ import {
subDays,
startOfHour,
startOfDay,
startOfWeek,
startOfMonth,
endOfHour,
endOfDay,
endOfWeek,
endOfMonth,
differenceInHours,
differenceInDays,
differenceInCalendarDays,
} from 'date-fns';
export function getTimezone() {
@ -23,23 +27,47 @@ export function getLocalTime(t) {
export function getDateRange(value) {
const now = new Date();
const hour = endOfHour(now);
const day = endOfDay(now);
const { num, unit } = value.match(/^(?<num>[0-9]+)(?<unit>hour|day)$/).groups;
const { num, unit } = value.match(/^(?<num>[0-9]+)(?<unit>hour|day|week|month)$/).groups;
if (+num === 1) {
switch (unit) {
case 'day':
return {
startDate: startOfDay(now),
endDate: endOfDay(now),
unit: 'hour',
value,
};
case 'week':
return {
startDate: startOfWeek(now),
endDate: endOfWeek(now),
unit: 'day',
value,
};
case 'month':
return {
startDate: startOfMonth(now),
endDate: endOfMonth(now),
unit: 'day',
value,
};
}
}
switch (unit) {
case 'day':
return {
startDate: subDays(day, num),
endDate: day,
startDate: subDays(startOfDay(now), num - 1),
endDate: endOfDay(now),
unit,
value,
};
case 'hour':
return {
startDate: subHours(hour, num),
endDate: hour,
startDate: subHours(startOfHour(now), num - 1),
endDate: endOfHour(now),
unit,
value,
};
@ -48,20 +76,22 @@ export function getDateRange(value) {
const dateFuncs = {
hour: [differenceInHours, addHours, startOfHour],
day: [differenceInDays, addDays, startOfDay],
day: [differenceInCalendarDays, addDays, startOfDay],
};
export function getDateArray(data, startDate, endDate, unit) {
const arr = [];
const [diff, add, normalize] = dateFuncs[unit];
const n = diff(endDate, startDate);
const n = diff(endDate, startDate) + 1;
function findData(t) {
return data.find(e => getLocalTime(e.t).getTime() === normalize(t).getTime())?.y || 0;
const x = data.find(e => new Date(e.t).getTime() === normalize(new Date(t)).getTime());
return x?.y || 0;
}
for (let i = 0; i < n; i++) {
const t = add(startDate, i + 1);
const t = add(startDate, i);
const y = findData(t);
arr.push({ t, y });

View file

@ -165,7 +165,7 @@ export async function getPageviewData(
return runQuery(
prisma.queryRaw(
`
select date_trunc('${unit}', created_at at time zone '${timezone}') t,
select date_trunc('${unit}', created_at at time zone '${timezone}') at time zone '${timezone}' t,
count(${count}) y
from pageview
where website_id=$1