CakePHP 3 Date format Issue
Asked Answered
H

1

1

I researched everywhere but could not find the solution,
In the database, I am using from_date field as date(2018-07-07) type But when I find the data then it auto converts in from_date to 'Cake\I18n\Date Object'

[from_date] => Cake\I18n\Date Object
        (
            [time] => 2018-07-07T00:00:00+00:00
            [timezone] => UTC
            [fixedNowTime] => 
        )

I what this as

[from_date] => '2018-07-07'

I know we can covert this by

$obj->from_date->format('Y-M-D');

but the data is coming in an array of 10000 loops, this is not a good idea to convert in the loop. I also tried this in bootstrap.php

Type::build('date')->useLocaleParser()->setLocaleFormat('y-m-d');

but this is also not working.

Please help

Hitherward answered 4/7, 2018 at 7:1 Comment(2)
there are many ways, but what is the reason you want to format the date?Truncated
I am converting this in JSON format & this format creating an issue in javascript. in JSON format, it shows 2018-07-07T00:00:00+00:00Hitherward
T
2

in your bootstrap.php you can set the default format you want when converting Date and FrozenDate to string in Json

see the manual here and the api here

note that you have to use string patterns described here and not the patterns you usually use with date()

so your code should be

\Cake\I18n\FrozenDate::setJsonEncodeFormat('yyyy-MM-dd'); 
\Cake\I18n\Date::setJsonEncodeFormat('yyyy-MM-dd'); 
Truncated answered 4/7, 2018 at 10:0 Comment(2)
You'd probably want to apply this on \Cake\I18n\Date/\Cake\I18n\FrozenDate instead. Also use yyyy, as YYYY represents the week-numbering year, which isn't always the same as the calendar year.Pe
i tried this \Cake\I18n\Date::setJsonEncodeFormat('yyyy-MM-dd'); now working,Hitherward

© 2022 - 2024 — McMap. All rights reserved.