laravel 中获取的数据会自动更改时间戳值

问题描述 投票:0回答:1

所以问题是我有一个 laravel vue 项目,两者都是不同的应用程序,并且我在

'timezone'='Aisa/Kolkata'
中的 config/app.php 中进行了更改,以便该应用程序显示我所在国家/地区的当地时间。一切都很好,就像向数据库添加新数据时时间戳是正确的,更新数据时时间戳也是正确的。但是当获取数据时,时间格式更改为 UTC 例如:-
2023-12-15 15:36:11
这是created_at字段,它的格式正确,创建时间也是正确的,但是从laravel中获取它时,时间将其格式更改为这个
2023-12-15T10:06:11.000000Z

下面是我的代码示例和屏幕截图:-

this is the table

这里的created_at字段的时间戳为

2023-12-15 15:36:11
,获取时间和数据的代码是

$res = AcCleaning::whereBetween('ac_cleaning_detail.created_at', [$startDate, $endDate])
      ->join('peon_masters as pm', 'pm.peon_id', '=', 'ac_cleaning_detail.peon_ref_id')
      ->join('ac_masters as am', 'am.ac_id', '=', 'ac_cleaning_detail.ac_ref_id')
      ->latest('ac_cleaning_detail.created_at')
      ->select('ac_cleaning_detail.created_at')
      ->get();

      if (sizeof($res) > 0) {
           return $this->successResponseWithData("Fetched Successfully", $res);
      } 
      else {
           return $this->errorResponseWithoutDataWithErrorCode("No Data!!", Config::get('constants.HTTP_STATUS_CODES.NO_CONTENT'));
      }

此代码为我提供了使用created_at时间戳清洁AC时的时间戳,但在检查邮递员中的数据时

{
    "status": true,
    "message": "Fetched Successfully",
    "data": [
        {
            "created_at": "2023-12-15T10:06:11.000000Z"
        }
    ]
}

格式和时间自动更改为另一个时区

下面是模型

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class AcCleaning extends Model
{
    use HasFactory;
    protected $primaryKey = 'ac_clean_id';
    protected $table = 'ac_cleaning_detail';
    public $fillable = ['peon_ref_id','ac_ref_id','longitude','latitude'];
    public $timestamps = true;
}

我检查了一堆解决方案,其中许多建议在模型中创建另一种方法,将时间戳更改为碳实例,但在获取大量数据时如何调用它。

另外为什么它会自动更改时间。我错过了什么请帮忙。

我只想在存储时间戳时获取它。我正在使用 laravel 10,php 8.2

php laravel eloquent timestamp laravel-10
1个回答
0
投票

我得到了答案,通过在模型中定义变异器,我克服了日期时间自动更改为另一个时区的问题。

只需将以下代码写入您的模型

 protected function serializeDate(DateTimeInterface $date): string
{
    return Carbon::parse($date);
}

它将自动更改为您在 config/app.php 中指定的指定时区

© www.soinside.com 2019 - 2024. All rights reserved.