I have a database storing data for my Laravel/PHP application. All data is stored in the database as UTC.
I'm writing a query to get data grouped by date and hour so I can plot the data on a graph.
Our UI shows reporting data in the America/Los_Angeles
timezone.
What I'm looking to do is get the last three days data but queried based on the reporting timezone of America/Los_Angeles
.
To get the BETWEEN
dates I'm using the below
$from = now()
->startOfDay()
->subDays(3)
->timezone('America/Los_Angeles');
$to = now()
->endOfDay()
->timezone('America/Los_Angeles');
This works OK. So the next step is grouping the data but not grouping it on the column data as that would be UTC
. I would like to group is on the Los_Angeles
timezone. So I'm doing the below.
SELECT
DATE(CONVERT_TZ(created_at, '+00:00', '-07:00')) AS grouped_date,
HOUR(CONVERT_TZ(created_at, '+00:00', '-07:00')) AS grouped_hour,
count(*) AS requests
FROM
`advert_requests`
WHERE
created_at BETWEEN '2022-09-09 17:00:00' AND '2022-09-13 16:59:59'
GROUP BY
grouped_date,
grouped_hour
The random issue I'm having is that the grouped data is starting on 2022-09-09
at 10:00
and I'm not sure why.
Starting the BETWEEN
at 2022-09-09 17:00:00 America/Los_Angeles
is 2022-09-10 00:00:00 UTC
so when doing the CONVERT_TZ
on the created_at
shouldn't the grouped data start at 0
?
Any ideas?
Surely this isn't as easy as just setting the timezone to the reporting timezone for the sessions where I run the reporting SELECT
query.
So I can leave everything else as UTC
. My application is UTC
and handles timezone conversion in the php/application. My database is set to UTC
. My MySQL INSERT
's etc are all UTC
. Then when I want to query anything to be displayed in our UI using our fixed reporting timezone of America/Los_Angeles
I can just set it before running the SELECT
query?
SET time_zone = '-07:00';
// In the Laravel framework
// DB::update('SET time_zone = ?', ['-07:00']);
And then
SELECT
DATE(created_at) AS grouped_date,
HOUR(created_at) AS grouped_hour,
count(*) AS requests
FROM
`advert_requests`
WHERE
created_at BETWEEN '2022-09-10 00:00:00'
AND '2022-09-13 23:59:59'
GROUP BY
grouped_date,
grouped_hour
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.