Reputation: 31
We run a Laravel app with MySQL DB. The DB consists of many entries relating to different pojects. The idea is that each project has its own timezone and outputs relevant entries with their dates formatted accordingly. Thus, in order to be able to change timezones and for compatibility sake, all entries are stored in UTC timezone (app default timezone is set to UTC as well). The problem is that, for instance, we need to get today's entries, but in project's timezone, not UTC. We use Carbon, but it only formats the date for output and still compares them in UTC timezone. For example, there is an entry made on December 7, 22.32 in UTC. But according to Europe/Moscow, it was made on December 8, 01.32, and it should be considered as today's entry for a project with Europe/Moscow timezone. Still, even with Moscow timezone given, Carbon considers it as yesterday's entry (according to UTC). We use whereDate in the query:
whereDate( 'created_at', Carbon::now($project->timezone)->startOfDay() )
The problem is that Carbon makes no difference between Carbon::now('UTC') and Carbon::now('Europe/Moscow'). It gives zero if you compare them:
$tz1 = Carbon::now('UTC');
$tz2 = Carbon::now('Europe/Moscow');
echo tz1->diffInHours(tz2) //0
What do I miss? How should I do it properly?
Upvotes: 2
Views: 2356
Reputation: 774
$tz1
and $tz2
have timezone info with them, and both contain information of now()
time. That's why there is no difference. Change the timezone data to make them sane timezone after retrieving using shiftTimezone()
.
so
$tz1 = Carbon::now('UTC');
$tz2 = Carbon::now('Europe/Moscow')->shiftTimezone('UTC');
echo tz1->diffInHours(tz2) //should be appropriate
Upvotes: 2