Home > Mobile >  Laravel timestamp columns saving with wrong date format
Laravel timestamp columns saving with wrong date format

Time:06-08

I recently updated an old laravel 5.7 project to 8.0 and the created_at and updated_at model timestamps get created with the wrong format. Back in the day i used this code in all models that are from a SQL Server database to get it working between my local and production environment.

public function getDateFormat()
{
    if (PHP_OS_FAMILY == 'Windows') {
        return 'Y-d-m H:i:s.v';
    } else {
        return 'Y-m-d H:i:s';
    }
}

I use windows to develop the application and a Linux server to run it with apache, but after updating the project the timestamps invert the day and month of the date. For example, if i create a model in the date '2022-06-07 13:00:00' the created_at timestamp will be '2022-07-06 13:00:00'.

Of course, changing the getDateFormat() method to only return 'Y-d-m H:i:s.v' in all environments works, but create another problem with php date function, for example, if i call <p> updated at: {{ date('d/m/Y H:i:s', strtotime($model->updated_at)) }}</p> the desired result would be updated at: 07/06/2022 13:00:00 but instead i get updated at: 06/07/2022 13:00:00.

I really dont know if this is a php timezone issue or something related to laravel, since the problem shows at saving/updating rows or displaying formatted data information.

CodePudding user response:

try

date("Y-d-m H:i:s", time());

CodePudding user response:

Please use:

updated at: {{ date('m/d/Y H:i:s', strtotime($model->updated_at)) }}

for the desired result as the above m shows month, d shows days similarly y shows year.

CodePudding user response:

Laravel have Carbon so use it for datetime stuff

use Carbon\Carbon;
...
if(! function_exists('format_date') {
    function format_date(string $date): string
    {
        return Carbon::parse($date)->format('d-m-Y H:i:s'); 
        // something like 31-12-2022 12:00:00, just change format as you need
    }
}

From your view:

{{ format_date($model->date) }}

Make sure to check Ref

  • Related