Stanleyy
Stanleyy

Reputation: 328

How to query for a day with timezone in Laravel

In my database I have the created_at column that stores datetime when a record was created in UTC time, I also have a column that stores the same datetime converted to the users timezone created_timezone.

In the code below I am trying to check if an entry for that day (with respect to the users timezone) was made

public static function isEntryMade($userID, $timezone)
{
    $day = Day::where('user_id', $userID)->whereDate('created_timezone', Carbon::today()->timezone($timezone))->get();
    return $day;
}

The problem is that the result is returning the previous day records, I am almost certain that this is because the timezone() method subtracts 5 hours due to the users timezone (America/Toronto).

How can I get this to return only the records that have been made today with respect to the users timezone.

For clarification, I am also storing the users timezone in the database and that is what $timezone is. Also, the created_timezone column is the created_at time but parsed for the users timezone

Upvotes: 1

Views: 1439

Answers (1)

STA
STA

Reputation: 34688

Use setTimezone() method :

Carbon::now('UTC')->setTimezone('America/Toronto') 

Here UTC is your app timezone

Upvotes: 1

Related Questions