Saturday, January 1, 2022

[FIXED] Laravel Create Date return different format

Issue

I tried to select the create_data from the database, the date format in the database is like "2021-05-18 11:06:01", but when I retrieve and display it, it's will show the format like is "2021-05-18T03:06:01.000000Z". Does anyone know why will become like that? I want the date which is actually like the database store which is "2021-05-18 11:06:01". However, the create_date inside DB the format is UTC +8, but when receive it will show UTC format.

enter image description here

Data return

[0] => Array (
    [id] => 1
    [log_name] => login
    [description] => login
    [subject_type] => App\Models\Users
    [subject_id] => 0
    [causer_type] => App\Models\User
    [causer_id] => 2
    [properties] => ""         
    [created_at] => 2021-05-18T03:06:01.000000Z
);

Code

$lastLoggedActivity = ActivityLog::where('causer_id', $userid)
    ->orWhereIn('subject_id', $selectparentid)
    ->with('getLogType')
    ->with('getCauserDetails')
    ->orderBy('created_at', 'desc')
    ->get()
    ->toArray();

Solution

Add a serializeDate method to your model to change it's format on responses.

/**
 * Prepare a date for array / JSON serialization.
 *
 * @param  \DateTimeInterface  $date
 * @return string
 */
protected function serializeDate(DateTimeInterface $date)
{
    return $date->format('Y-m-d H:i:s');
}


Answered By - jrcamatog

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.