简体   繁体   中英

Laravel whereDate user timezone

How do I query results in the users timezone?

All my users have a timezone attribute, eg:

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?

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!

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM