Home > Enterprise >  How to remove time from date in yajra datatable
How to remove time from date in yajra datatable

Time:04-18

I am using Laravel yajra datatable and I want to show only date in column , but unfortunately I am also getting time please help me how can I show date ?

enter image description here

start date and and date should be like that in date column.

2022-04-17 - 2022-04-23

BookingController

  public function datatables()
    {

        $booking = Booking::select(['id','start_datetime','end_datetime'])->get();

        return Datatables::of($booking)
        ->addColumn('mergeColumn', function($row){
        return $row->start_datetime.' - '.$row->end_datetime;
        })
        ->make(true);
    }

Jquery Script

 $(document).ready(function() {

    var table = $('#users-table').DataTable({
        processing: true,
        serverSide: true,
        ajax: "{{ route('datatables.data') }}",
        "columns": [
            {
                "data": "mergeColumn",
                "defaultContent": ""
            },

        ],
        "columnDefs": [{
                "targets": 'no-sort',
                "orderable": false,
            },
              {
            "targets": 0,
            "render": function(data, type, row, meta) {
                    return  data;
            },
        },

        ],
        "drawCallback": function (settings) {
      },
        //scrollX:true,
    });

    });

CodePudding user response:

You can use the Carbon library in Laravel to parse your datetime strings and format them in any way you like. The controller code would look something something like this:

use Illuminate\Support\Carbon;

// ...

public function datatables()
{
    $booking = Booking::select(['id','start_datetime','end_datetime'])
        ->get()
        ->map(function($booking) {
            $start = Carbon::parse($booking->start_datetime);
            $end = Carbon::parse($booking->end_datetime);
            return [
                'id' => $booking->id,
                'start_date' => $start->format('Y-m-d'),
                'end_date' => $end->format('Y-m-d'),
            ];
        });

    return Datatables::of($booking)
        ->addColumn('mergeColumn', function($row){
            return $row['start_date'] . ' - ' . $row['end_date'];
        })
        ->make(true);
}

You can get the time values from the $start and $end variables too if you need them.

  • Related