我想知道是否有可能,假设我有一个这样的模型:
MyModel
SomeDate - Carbon
现在,我还为当前用户设置了时区,代码如下:
User
MyTimezone
数据库中存储的时区始终以UTC格式存储(以确保一致性),输出的日期应始终格式化为特定时区(但每个用户的时区不同),例如User1的时区为America/Chicago,而User2的时区为America/Denver。
是否有一种方法可以在输出之前自动将每个Carbon实例的时区格式化为给定的时区,还是我必须循环遍历集合并相应地设置每个实例?
设置app.timezone无效,因为它还会导致Carbon实例以app.timezone时区保存到数据库中,而数据库中的所有日期都应该是UTC,因此我失去了一致性。
我当前将app.timezone设置为App配置中的UTC,但我也被迫在输出之前将所有Carbon实例转换为正确的时区。是否有更好的方法,例如在Carbon转换为字符串之前捕获执行并在那里进行操作?
编辑:
我尝试过的事情:
覆盖setAttribute和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;
}
覆盖 asDateTime 方法:
protected function asDateTime($value)
{
// If this value is an integer, we will assume it is a UNIX timestamp's value
// and format a Carbon object from this timestamp. This allows flexibility
// when defining your date fields as they might be UNIX timestamps here.
$timezone = Helper::fetchUserTimezone();
if (is_numeric($value))
{
return Carbon::createFromTimestamp($value, $timezone);
}
// If the value is in simply year, month, day format, we will instantiate the
// Carbon instances from that format. Again, this provides for simple date
// fields on the database, while still supporting Carbonized conversion.
elseif (preg_match('/^(\d{4})-(\d{2})-(\d{2})$/', $value))
{
return Carbon::createFromFormat('Y-m-d', $value, $timezone)->startOfDay();
}
// Finally, we will just assume this date is in the format used by default on
// the database connection and use that format to create the Carbon object
// that is returned back out to the developers after we convert it here.
elseif ( ! $value instanceof DateTime)
{
$format = $this->getDateFormat();
return Carbon::createFromFormat($format, $value, $timezone);
}
return Carbon::instance($value);
}