Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Zaheer's avatar

Cannot display date

I am using following code to display a datetime value from mysql table to a datetime-local input element.

$('#date').text(data.invoice['date'].toString('Y-m-dTH:i'));

But instead of showing date from table it is displaying current date. What I am doing wrong ?

0 likes
10 replies
Snapey's avatar

How have you converted the json sent from your controller into a date object?

Zaheer's avatar

@SNAPEY - I am getting this value from data.invoice['date'] 2019-05-23 16:05:00

and my controller code is :

        $invoice = Purchase::find($id)->toArray();
        $items = Purchase::find($id)->items->toArray();
        return response()->json(array('invoice'=>$invoice,'items'=>$items));

UPDATE : here is the Input element :

<input type="datetime-local" class="form-control" name="date" id="date" value="<?php echo date('Y-m-d');echo 'T';echo date ('H');echo ':';echo date('i');?>" required="required">
Snapey's avatar

Totally different code now then?

Zaheer's avatar

@SNAPEY - THEN was ajax code and NOW is the supporting code. Ajax code is displaying result from controller code to an in Input element.

Snapey's avatar

So back to my original observation. You have sent a string (which happens to be a date) to the client but then you are trying to apply date formatting to it. You would need to convert it to a javascript date object before you could do that.

Alternatively in your Purchase model;

create a getter and append it to the response

protected $appends = ['formattedDate'];

public getFormattedDateAttribute()
{
    return $this->date->format('Y-m-d\TH:i');
}

assumes you have already told eloquent that date should be cast to Carbon

and then use $('#date').text(data.invoice['formattedDate'])

Alternatively

https://laravel.com/docs/5.8/eloquent-serialization#date-serialization

jlrdw's avatar

Have you tried just:

$('#date').val(data.invoice['date']);
Zaheer's avatar

@SNAPEY - It throws following error : LOG.error: Call to a member function format() on string {"userId":161,"exception":{}}

My model code is as under : (have i done it right ?)

class Purchase extends Model
{
    //
    protected $guarded = [];
    protected $appends = ['formattedDate'];

    public function getFormattedDateAttribute()
    {
    return $this->date->format('Y-m-d\TH:i');
    }
}
Snapey's avatar

assumes you have already told eloquent that date should be cast to Carbon

Zaheer's avatar

I am new to web development and Laravel. Was unable to understand Carbon. Ended up using Moment.js

$('#date').val(moment(data.invoice.date).format("YYYY-MM-DDTHH:mm"));

Please or to participate in this conversation.