Search code examples
phplaraveltimezonephp-carbon

Converting date to UTC with Laravel function


I'm trying to convert an incoming date with a specific timezone to UTC. My code looks like this (please see comments for date/timezone):

convertToUTC(
    $request->scheduled_at, //2023-05-13T12:00:00.000Z
    $request->user()->company->timezone, //Europe/Amsterdam
); 

function convertToUTC($timestamp, $timezone)
{
    $carbon = new \Carbon\Carbon($timestamp, $timezone);

    $carbon->setTimezone('UTC');

    $utcTimestamp = $carbon->toDateTimeString();

    return $utcTimestamp;
}|

I would expect the output to be:

2023-05-13T10:00:00.000Z

Because Amsterdam is 2 hours behind UTC. However, I keep receiving 2023-05-13T12:00:00.000Z(no change). Why is it not converted correctly to utc?


Solution

  • The Z at end of timestamp means Zero Timezone (Zulu Time Zone) as it offset by 0 from UTC for detailed explanation you can see this thread on stackoverflow. and here's list of military time zones that contains explanation for every letter. You can also use B at the end for +2hr offset as listed in list of timezones.