I have some data that I want to report on (simplified for brevity):
MyDateTime (UTC) MyValue
------ -------
2020-10-01 10:00:00 24
2020-10-01 15:00:00 53
2020-10-02 12:00:00 26
etc
All dates are stored as UTC. Normally, I would keep everything in UTC for as long as possible, and convert to the local time in the users browser based on the users locale.
However for this particular report, I want to aggregate the data by whole dates:
SELECT CAST(MyDateTime AS DATE), AVG(MyValue)
FROM MyTable
GROUP BY CAST(MyDateTime AS DATE)
So I need to convert the date to the user's local time before I truncate the MyDateTime
column and aggregate it.
In SQL Server, I can convert the UTC datetime
to a local truncated date like this:
CAST(CONVERT(datetime2, (SeizeTime AT TIME ZONE 'GMT Standard Time'), 1) AS DATE)
SQL Server has a list of timezone names that the AT TIME ZONE
clause accepts, in my example I'm using GMT Standard Time
which is UK time including daylight savings.
Javascript running in a browser has another way of naming timezones:
console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)
--> Europe/London
So my problem is that there is no common way of naming timezones between SQL Server and Javascript. How can I reliably map Europe/London
to GMT Standard Time
, along with all the other possible timezones in the world?
My options to get around this so far are:
- Use a hard-coded lookup table - could break if timezone info changes in the future.
- Send all the pre-aggregated data to the browser, apply the timezone to the date and then aggregate the data on the client - I want to avoid moving too much data around unnecessarily.
Is there any other way to do this that I'm missing?