其實寫這支 Cast 是之前為了應付 LARAVEL 本身的 ORM 的日期呼叫方式。
再加上,其實我當時本身也比較愛用 unixtime 來記錄時間。
所以就寫了這一支萬用的處理。
二話不說,先直接上程式碼
然後記得你的LARAVEL的時區設定,一般會是在 config/app.php 中的一個 timezone 變數值。
請調整 「Asia/Taipei」或是其它你想要的時區。
這樣在ORM中,你只要如下宣告即可
後面就是你想要出現的日期格式。
這樣資料再輸出時,就會出現正確的時區。
就算您欄位是使用使用 unixtime 也可以正常轉換。
再加上,其實我當時本身也比較愛用 unixtime 來記錄時間。
所以就寫了這一支萬用的處理。
二話不說,先直接上程式碼
PHP:
<?php
namespace App\Casts;
use DateTime;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
/**
* 對應的日期欄位,轉換成依app設定值的本地時間
* Class LocalDateTime
*
* @package App\Casts
*/
class LocalDateTime implements CastsAttributes
{
protected $format;
public function __construct($format = null)
{
$this->format = $format ?: 'Y-m-d H:i:s';
}
/**
* Cast the given value.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param mixed $value
* @param array $attributes
*
* @return string
* @throws \Exception
*/
public function get($model, $key, $value, $attributes)
{
if (!$value) {
return '';
}
if (is_numeric($value)) {
$value = gmdate('Y-m-d H:i:s.Z', $value).'Z';
}
$date = new DateTime($value);
$timezone = new \DateTimeZone(config('app.timezone'));
$date->setTimezone($timezone);
return $date->format($this->format);
}
/**
* Prepare the given value for storage.
*
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param array $value
* @param array $attributes
*
* @return array
*/
public function set($model, $key, $value, $attributes)
{
return $value;
}
}
然後記得你的LARAVEL的時區設定,一般會是在 config/app.php 中的一個 timezone 變數值。
請調整 「Asia/Taipei」或是其它你想要的時區。
這樣在ORM中,你只要如下宣告即可
PHP:
protected $casts = [
'created_at' => LocalDateTime::class.':Y-m-d',
'updated_at' => LocalDateTime::class.':Y-m-d H:i:s',
];
後面就是你想要出現的日期格式。
這樣資料再輸出時,就會出現正確的時區。
就算您欄位是使用使用 unixtime 也可以正常轉換。