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

bayof's avatar

Date Format

Hi, i'm having problems formatting the dates, i have a table in mysql with three dates timeinit, created_at, updated_at, to first one i want to give it a format like this, '2015-10-21 11:31:00.523000', so i read in the documentation that i have to use the $dateFormat property in my model like this: protected $dateFormat = 'Y-m-d h:i:s.u'; But when i do this the other two dates (created_at and updated_at) fail, this two dates are the regular dates from laravel, the documentation also says that i can use the $date field that specified the dates are going to be mutated like this: protected $dates = ['timeinit']; But my app keep failing saying that the format for created_at is not like 'Y-m-d h:i:s.u'.

i decided to insert the dates manually, using DB::table('trxes')->insert(), works greate, it saves the time with the .u format, but when i list the data in my view it doesn't show the microseconds and i need it.

i think i have to use a mutator for this, so i create one,

public function getTimeinitAttribute($date){ $dt = new \DateTime($date); return Carbon::instance($dt)->format('Y-m-d h:i:s.u') }

but the view still shows 2015-10-21 11:31:00

0 likes
3 replies
bayof's avatar

Ok, the format it's "working", but it has a problem, the view shows 2015-10-21 11:31:00.000000, but in the database, the date is 2015-10-21 11:31:00.132000.

I went to php artisan tinker, and executed App\Trx::all(); this shows the date without the decimals, i think this is the problem, when i call to the function in my controller it returns the same data as the tinker, so, the date never had the decimals and that why it returns .000000, someone knows how to format the column at the time is consulted in the database? or maybe cast it to a string at the database level.

this is how i am consulting to the database in my controller, $var=DB::table('trxes)->where('created_at','<','now()+INTERVAL 1 DAY')->first();

thomaskim's avatar

@bayof I don't believe the PHP PDO driver supports fractional seconds.

What you probably have to do is fetch it as a string. I just added a selectRaw statement to fetch everything and fetch timeinit as a string.

$var = DB::table('trxes')->where('created_at','<','now()+INTERVAL 1 DAY')->selectRaw("*, CONCAT(timeinit) as timeinit")->first();

Please or to participate in this conversation.