Skip to content

Commit

Permalink
Fix timezone bug in intervalToSql (fixes #77)
Browse files Browse the repository at this point in the history
  • Loading branch information
benvinegar committed Apr 30, 2024
1 parent e48cb06 commit f0e419e
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 3 deletions.
20 changes: 19 additions & 1 deletion app/analytics/query.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import {
Mock,
} from "vitest";

import { AnalyticsEngineAPI } from "./query";
import { AnalyticsEngineAPI, intervalToSql } from "./query";

function createFetchResponse<T>(data: T) {
return {
Expand Down Expand Up @@ -289,3 +289,21 @@ describe("AnalyticsEngineAPI", () => {
});
});
});

describe("intervalToSql", () => {
// test intervalToSql
test("should return the proper sql interval for 1d, 30d, 90d, etc (days)", () => {
expect(intervalToSql("1d")).toBe("NOW() - INTERVAL '1' DAY");
expect(intervalToSql("30d")).toBe("NOW() - INTERVAL '30' DAY");
expect(intervalToSql("90d")).toBe("NOW() - INTERVAL '90' DAY");
});

test("should return the proper tz-adjusted sql interval for 'today'", () => {
expect(intervalToSql("today", "America/New_York")).toBe(
"toDateTime('2024-04-29 04:00:00')",
);
expect(intervalToSql("today", "America/Los_Angeles")).toBe(
"toDateTime('2024-04-29 07:00:00')",
);
});
});
4 changes: 2 additions & 2 deletions app/analytics/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,12 @@ function accumulateCountsFromRowResult(
counts.views += Number(row.count);
}

function intervalToSql(interval: string, tz?: string) {
export function intervalToSql(interval: string, tz?: string) {
let intervalSql = "";
switch (interval) {
case "today":
// example: toDateTime('2024-01-07 00:00:00', 'America/New_York')
intervalSql = `toDateTime('${dayjs().startOf("day").format("YYYY-MM-DD HH:mm:ss")}', '${tz}')`;
intervalSql = `toDateTime('${dayjs().tz(tz).startOf("day").utc().format("YYYY-MM-DD HH:mm:ss")}')`;
break;
case "1d":
case "7d":
Expand Down

0 comments on commit f0e419e

Please sign in to comment.