My app timezone is set to 'America/Montreal'.
I have a two datetime fields 'start' and 'end', each casted to datetime using laravel $casts property:
protected $casts = [
'start' => 'datetime',
'end' => 'datetime'
];
When I create an instance of my model with the following data:
MyModel::create(
[
'start' => "2022-02-08T20:45:58.000Z", // UTC time
'end' => "2022-02-08T20:45:58.000Z",
]
);
The created model keeps the same time (20:45) but the timezone is set to America/Montreal:
App\MyModel {#4799
id: 44,
created_at: "2022-02-08 15:49:02",
updated_at: "2022-02-08 15:49:02",
start: 2022-02-08 20:45:58,
end: 2022-02-08 20:45:58,
}
when I access the start and end attributes I get the same time but with America/Montreal timezone like this:
// accessing 'start' attribute of the instance I just created
Illuminate\Support\Carbon @1644371158 {#4708
date: 2022-02-08 20:45:58.0 America/Montreal (-05:00),
}
The only way I found to get it to work correctly is to manually setTimezone before saving:
MyModel::create(
[
'start' => Carbon::parse("2022-02-08T20:45:58.000Z")->setTimeZone(config('app.timezone')),,
'end' => Carbon::parse("2022-02-08T20:45:58.000Z")->setTimeZone(config('app.timezone')),,
]
);
which is, I think, repetitive, isn't setting the app timezone enough ? Is there any better way to do this ? I know that I'm supposed to set my app timezone to UTC (which is what I do usually) but this projet has already a lot of data with this timezone and I'm not sure how to convert it.
Thank you.