Reputation: 1267
How do I query results in the users timezone?
All my users have a timezone
attribute, e.g.:
Auth::user()->timezone; // America/Toronto
The app config timezone and the database timezone are set to UTC. Each user can have a different timezone. The problem is I'm trying to filter records for today
, and its giving me results from yesterday as well:
$query->whereDate($column, Carbon::now())
I know this is because of the offset. I've tried using this which does not make a difference:
$query->whereDate($column, Carbon::now()->tz(Auth::user()->timezone)
How do I grab the correct results for the current day in the user timezone based on the database values using UTC?
Upvotes: 1
Views: 2497
Reputation: 461
You could try adding a date range like this:
$query->whereDate($column, ">=", Carbon::now()->startOfDay()->tz(Auth::user()->timezone)
->whereDate($column, "<=", Carbon::now()->endOfDay()->tz(Auth::user()->timezone);
The key here would be determining the start and end of the current day using the default timezone, and then converting those timestamps to the current user's timezone.
I hope this helps!
Upvotes: 1