yajra / laravel-datatables

jQuery DataTables API for Laravel
https://yajrabox.com/docs/laravel-datatables
MIT License
4.74k stars 861 forks source link

Issue with timestamps & datetimes format (on the latest version of this package?) #2640

Closed PeraMika closed 1 year ago

PeraMika commented 3 years ago

Summary of problem or feature request

Timestamps are displayed with milliseconds. For example I have:

$users = User::select(['id', 'name', 'email', 'created_at', 'updated_at']);

        return Datatables::of($users)
            ->make(true);

and created_at is displayed like this:

2018-06-19T23:04:50.000000Z

However, if I just add this:

            ->editColumn('created_at', function ($user) {
                return $user->created_at; // no formatting, just returned $user->created_at; 
            })

Then it will be displayed like this:

2018-06-19 23:04:50

So I didn't format or do anything with created_at, I just returned $user->created_at and in that case it's shown as expected.

Also, in DB in users table created_at values are like this: 2018-06-19 23:04:50. Finally, I already have created_at in protected $dates in User.php model.

This is probably a bug because it didn't exist before I upgraded to the latest version of Laravel and yajra/laravel-datatables package.

yajra commented 3 years ago

This is the new behavior of Laravel Framework when using toArray() and not the package as far as I remember.

Also, if I recall correctly, using editColumn will trigger the internal formatter of the package for date which the reason for the output.

yajra commented 3 years ago

This is how I handle dates on Laravel 8 if it helps.

namespace App\DataTables\Formatters;

use DateTime;
use Yajra\DataTables\Contracts\Formatter;

class DateFormatter implements Formatter
{
    /**
     * @var string
     */
    public $format;

    public function __construct($format = 'Y-m-d h:i a')
    {
        $this->format = $format;
    }

    public function format($value, $row)
    {
        if ($value instanceof DateTime) {
            return $value->format($this->format);
        }

        return $value ? carbon($value)->format($this->format) : '';
    }
}
    public function dataTable($query)
    {
        return datatables()
            ->eloquent($query)
            ->formatColumn(['created_at', 'updated_at'], DateFormatter::class)
...

    protected function getColumns(): array
    {
        return [
            ...
            Column::formatted('created_at'),
            Column::formatted('updated_at'),
github-actions[bot] commented 1 year ago

This issue is stale because it has been open for 30 days with no activity. Remove stale label or comment or this will be closed in 7 days.

github-actions[bot] commented 1 year ago

This issue was closed because it has been inactive for 7 days since being marked as stale.