How do I change the timestamp format in CakePHP?

In my application, I am retrieving the timestamp from a table that is in the format 2009-08-18 12:09:01 . I need to change this before Aug 18, 2009 or Aug 18, 2009. How do I achieve this in CakePHP?

Are there any built in methods?


source to share

4 answers

You can use strptime to parse the string into datetime and then strftime to format it back to the desired string.



You can use the core TimeHelper

to format and test date / time.

To use it you need to add array TimeHelper

to your controller $helpers


var $helpers = array('Time');


Then, from the view, you can format the date / time variables:

// assuming $variable['Model']['field_name'] = '2009-09-09 12:00:00':
echo $this->Time->format('F jS, Y', $variable['Model']['field_name']);
// => 'September 9th, 2009'
echo $this->Time->format('j M Y', $variable['Model']['field_name']);
// => '9 Sep 2009'


Since this method is ultimately a wrapper, use the table in the PHP documentation for the function date()

to determine how to write the format.

Since version 1.3, if you change the order of the parameters (date first and then in the second format), it will try to evaluate your language's date format. The above ordering will still work for backward compatibility. More details at the bottom of this page in the migration guide.



Use the time helper as deizel mentioned.

I went through the /cake/libs/view/helpers/time.php file to see if there is a function in there that provides the time format you are after.

The relative functions of time are especially nice:

<?php echo $time->nice($dateValue); ?>
<?php echo $time->timeAgoInWords($dateValue); ?>


You can learn a lot from reading the CakePHP source.



This should do:

<?php echo date('M js Y', strtotime($post['Post']['date'])); ?>


Here Post is the name of the model and date is the name of the field.



All Articles