I was wondering if this is possible, so let me say that I have such a model:
MyModel
SomeDate - Carbon
Now I also have a time zone for the current user:
User
MyTimezone
the time slots stored in the database are always stored in UTC (to ensure that everything is consistent), and the output dates should always be formatted in a specific time zone (but the time zone is different for each user), for example America / Chicago for User1 and America / Denver for User2.
Is there a way to automatically format the time intervals per Carbon instance to the specified one before the output, or will I need to scroll through the collection and set each of them accordingly?
The setup app.timezonedoes not work, as it also causes Carbon instances to be stored in the database in the time zone app.timezone, while all dates in the database must be in UTC, so I lose consistency.
I currently app.timezonehave UTC set in the application configuration, but I also have to convert all Carbon instances to the correct time zone before output. Is there a better way, maybe capturing a penalty, before Carbon turns into a string and does it there?
EDIT:
Things I tried:
Replace setAttribute and getAttribute:
public function setAttribute($property, $value) {
if ($value instanceof Carbon) {
$value->timezone = 'UTC';
}
parent::setAttribute($property, $value);
}
public function getAttribute($key) {
$stuff = parent::getAttribute($key);
if ($stuff instanceof Carbon) {
$stuff->timezone = Helper::fetchUserTimezone();
}
return $stuff;
}
override asDateTime:
protected function asDateTime($value)
{
$timezone = Helper::fetchUserTimezone();
if (is_numeric($value))
{
return Carbon::createFromTimestamp($value, $timezone);
}
elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $value))
{
return Carbon::createFromFormat('Y-m-d', $value, $timezone)->startOfDay();
}
elseif ( ! $value instanceof DateTime)
{
$format = $this->getDateFormat();
return Carbon::createFromFormat($format, $value, $timezone);
}
return Carbon::instance($value);
}