Cakephp 3 giving date and time fields in frozentime object
Asked Answered
L

4

10

I am using cakephp 3.2 and when i am retrieving data by find query it is giving date fields in this format

Array
(
[0] => Cake\I18n\FrozenDate Object
    (
        [date] => 2016-08-01 00:00:00
        [timezone_type] => 3
        [timezone] => UTC
    )
)

and time fields in frozentime

Cake\I18n\FrozenTime Object
(
 [date] => 2016-10-11 10:00:00
 [timezone_type] => 3
 [timezone] => UTC
)

I need a common setting or global solution for complete site. So when i fetch the data by find query from database it should give me date time in simple format without any frozendate object.

like this

Array(
 [0] => 2016-08-01
)
Lydell answered 11/10, 2016 at 5:13 Comment(3)
None of the answers to date seem to meet the OP's request that "I need a common setting or global solution ... so when i fetch the data ... it should give me date time in simple format without any frozendate object." Current answers require code changes everywhere the date is used.Leath
@Leath Maybe ndm's answer for "Cakephp 3.2 change default date format" is of help?Chanda
Related: Convert time object of cakephp 3 in Y-m-d format and CakePHP 3 Date format IssueChanda
B
8

Simply call ->format('Y-m-d') on your Cake\I18n\FrozenDate object.

There's no need for Cake\I18n\FrozenDate::setToStringFormat() or $this->Time->format()

Baiel answered 30/5, 2019 at 14:19 Comment(1)
Would like to add that Cake\I18n\FrozenTime is a valid argument to \Datetime::diff() as well.Sidonie
B
4

In boostrap.php add

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

still it comes with forzenDate object with same params But when you will print in view then it will print the proper format

echo $var->created;  // print: 2016-08-01

Reference for Dates Datetime Format Syntax

Bedesman answered 11/10, 2016 at 6:54 Comment(1)
@Irshad Khan Thank you for adding the Datetime Format syntax link to this answer. I was looking for what date syntax it follows to fix my code. I wouldn't know it doesn't follow the regular PHP syntax formats if it weren't for your edit.Chanda
W
2

You can also use TimeHelper for formating datetime in View

Example

echo $this->Time->format(
  $YourDateTimeVariable, #Your datetime variable
  'Y-MM-d'               #Your custom datetime format
);

CakePHP TimeHelper function details is Here

Wallen answered 11/10, 2016 at 18:54 Comment(0)
S
0

You can directly print the date object in any custom date format by using inbuilt i18nFormat function.

$frozenDateObj->i18nFormat('dd-MMM-yyyy');

Use datetime-syntax reference for more customization

Septima answered 18/1, 2021 at 19:3 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.