[英]How to change time zome in different tables in Laravel
你能給個主意嗎? 我在 postgresql 數據庫中有兩個表。 由兩個單獨的 csv 文件填充記錄。 但是第一個 csv 文件的記錄帶有本地時間戳。 第二個 csv 文件的時間戳為 UTC。 因此,我需要更改此表中視圖的本地時間,該表中充滿了時區 UTC 的記錄。 在我需要在每個頁面中使用帶有此代碼的 laravel 之前,我曾經處理過這個問題,例如:
date_default_timezone_set('Europe/Sofia');
控制器:
function getdata_chart(Request $request)
{
$start_date = date('d-m-Y 00:00:00');
$end_date = date('d-m-Y 23:59:59');
if($request->start_date != '' && $request->end_date != '')
{
// if user fill dates
$dateScope = array($request->start_date ." 00:00:00", $request->end_date ." 23:59:59");
} else {
// default load page - today
$dateScope = array($start_date, $end_date);
};
$students = MeasCanal::whereBetween('recordtime', $dateScope)
->selectRaw('recordtime')
->selectRaw('max(formattedvalue) filter (where fullname = \'Данни.Кота\') as iazovir')
->selectRaw('max(formattedvalue) filter (where fullname = \'Данни.Температура\') as temperatura350')
->where(function ($query) {
$query->where('fullname', 'like', "Язовир.Данни.Кота")
->orWhere('fullname', 'like', "ГСК_11_350.Данни.Температура");
})
->groupBy('recordtime')
->orderBy('recordtime')
->get();
return response()->json($students);
}
return response()->json($students);
}
我不確定這是您想要的,但我認為您可以理解。
第一種方法,
您可以使用訪問器;
public function getCustomTimestampAttribute($value)
{
// you can use your logic here to set your timezone by table
$timezone = 'Europe/Sofia';
return Carbon::parse($this->custom_timestamp)->timezone($timezone)->toDateTimeString();
}
那么你可以得到這樣的值: $model->custom_timestamp
第二種方法,
您可以使用地圖;
$customDates = $dates->map(function ($date, $key) {
$date->custom_timestamp = Carbon::parse($date->custom_timestamp)->timezone('Europe/Sofia')->toDateTimeString();
return $date;
});
編輯
在您的模型(MeasCanal)中設置記錄時間屬性;
public function getRecordtimeAttribute($value)
{
// you can use your logic here to set your timezone by table
$timezone = 'Europe/Sofia';
return Carbon::parse($this->recordtime)->timezone($timezone)->toDateTimeString();
}
然后您可以簡單地在控制器中查看查詢后的結果,例如
dd($students);
甚至更簡單地看到:
dd($students->first()->recordtime); // first matched rows recordtime attr.
注意:您不能在原始查詢中使用訪問器,您應該使用 eloquent 模型順便說一句。
更新您的模型 MeasCanal 並添加以下內容:
導入和使用:
use Carbon\Carbon;
添加功能:
/**
* Get the user's recordtime.
*
* @param string $value
* @return string
*/
public function getRecordtimeAttribute($value)
{
return Carbon::parse($value)->timezone('Europe/Sofia')->toDateTimeString();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.