D
D
Dmitry Kuznetsov2021-04-22 10:03:48
Laravel
Dmitry Kuznetsov, 2021-04-22 10:03:48

Date discrepancy in the database and output in Laravel, how to solve the problem?

Good afternoon.

The bottom line is this:
Laravel 6 is used.
Data is stored in the database in a normal format: " 2019-04-10 00:00:00 ".
In the model, I am converting through protected $dates . And everything comes out fine.
But when outputting to another model, it turns out that this date is displayed in this format: " 2021-04-12T21:00:00.000000Z ". Those. 3 hours less.

How can I fix this problem? The option with an increase of +3 hours will not work. I once saw a solution to this problem a long time ago, but I can not find it. Help me please. Thanks in advance.

PS: it is highly undesirable to convert the date to another format, since it will have to be changed in many files, and this is another crap ...

Answer the question

In order to leave comments, you need to log in

2 answer(s)
P
part_os, 2021-04-22
@part_os

config/app.php
Look at the time zone here, try changing it to the one you need

A
Andrej Kopp, 2021-04-24
@sequelone

Alternatively, you can write your own function in Helper. For example, you need to add to the composer.json file in the "autoload" section:

"autoload": {
        ...,
        "files": [
            "app/Helpers/functions.php"
        ]
    },

to get:
"autoload": {
        "psr-4": {
            "App\\": "app/",
            "Database\\Factories\\": "database/factories/",
            "Database\\Seeders\\": "database/seeders/"
        },
        "files": [
            "app/Helpers/functions.php"
        ]
    },

Then, in the app folder, create the Helpers folder, and in it the functions.php file . Now you can add any functions to this file that can be called anywhere. Here is an example of usage:
<?php

use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

    function formattedDate($value) {
        $date = new \DateTime($value);
        $intlFormatter = new IntlDateFormatter('ru_RU', IntlDateFormatter::GREGORIAN, IntlDateFormatter::SHORT);
        $intlFormatter->setPattern('d MMMM YYYY в HH:mm');

        $formattedDate = $intlFormatter->format($date);

        return $formattedDate;
    }

And in the Blade template, where necessary, we call the function {{ formattedDate($item->created_at) }}
This function will convert different output data formats.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question