How to handle timezones when storing usage statistics in a database?

20 Views Asked by At

I have issue with timezones and statistics for my application. Each day I collect statistics for report table for previous day.

report table structure:

id: int,
date: UTC time
type: type_1 | type_2
status: success | error

statistic table structure (where each record store data for success/error reports for each type per day):

date: UTC time (date of the collected reports)
report_type: type_1 | type_2
reports: {
  success: []
  errors: []
}

let's assume there is a report:

{
  "id": 1,
  "date": "Sun May 21 2023 22:31:23 GMT+0000",
  "type": "type_1"
  "status": "success"
}

and two records with statistic for this report (for May 21 and May 22)

{
  date: Mon May 21 2023 23:59:59 GMT+0000
  report_type: type_1
  reports: {
    success: [1]
    errors: []
  }
}

{
  date: Mon May 22 2023 23:59:59 GMT+0000
  report_type: type_1
  reports: {
    success: []
    errors: []
  }
}

it works perfectly when I read statistics in UTC timezone, but when my timezone is CEST then report's date changes from May 21 to May 22 ("Sun May 21 2023 22:31:23 GMT+0000" + 2 hours = "Mon May 22 2023 00:31:23") but in statistic's data this report is still in May 21 record.

I see two options how to deal with it:

  1. calculate statistics on the fly for current timezone
  2. precalculate and save to db statistic for each needed timezone

maybe you have better ideas or know patterns to resolve this issue?

0

There are 0 best solutions below