Cakephp 3.2 change default date format

扶醉桌前 提交于 2019-11-28 01:38:41

I guess you have been upgrading to CakePHP 3.2, otherwise you'd have seen in your config/bootstrap.php file that there are separate types for DATE, DATETIME and TIME type columns.

With CakePHP 3.2 the date type doesn't mape to Cake\I18n\Time anymore, but to \Cake\I18n\Date (or \Cake\I18n\FrozenDate when instructed to use immutable objects), and it needs to be configured separately, which is why changing the datetime type, or the \Cake\I18n\Time class config won't affect your DATE columns.

To configure formatting for the latter, use the \Cake\I18n\Date and/or \Cake\I18n\FrozenDate class and the date type. In your bootstrap, you could do something like

ini_set('intl.default_locale', 'pl_PL');

// ...

Cake\I18n\Date::setToStringFormat('yyyy-MM-dd');
Cake\I18n\FrozenDate::setToStringFormat('yyyy-MM-dd');

\Cake\Database\Type::build('date')
    ->useImmutable()
    ->useLocaleParser()
    ->setLocaleFormat('yyyy-MM-dd');

That would override the defaults that are being applied when using the pl_PL locale. Note that you should use yyyy instead of YYYY (as the latter defines the week-numbering year), and MM instead of mm (as the latter defines minutes).

See http://www.icu-project.org/apiref/icu4c/classSimpleDateFormat.html#details for the format used by the intl formatter that CakePHP uses internally.

Also note that there's also \Cake\I18n\Date::$wordFormat and \Cake\I18n\Date:$niceFormat which you may want to change too.

See also

after a lot of searching I found.

In the config/app.php under the 'App' => []

change

'defaultLocale' => env('APP_DEFAULT_LOCALE', 'us_US'),

to

'defaultLocale' => env('APP_DEFAULT_LOCALE', 'pl_PL'),

and all your date will change to your formatting. because in config/boostrap.php it read

ini_set('intl.default_locale', Configure::read('App.defaultLocale'));

end in the cake\I18n FrozenDate it set to

protected static $_toStringFormat = [IntlDateFormatter::SHORT, -1];
manish kumar

Paste this code in this file config/site.php:

return [
 'Site' => [      
        'CakeDateFormat' => 'Y-M-d',
        'DatePickerFormat' => 'mm/dd/yyyy',
        'CakeDateFormatForView' => 'm/d/Y',        
    ]
]

Use this date format in controller:

use Cake\I18n\Time;

$this->request->data['date'] =Time::parseDate($this->request->data['date'], Configure::read('Site.CakeDateFormat'));

Set the date format according to your needs in CakeDateFormat.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!