CakePHP 3 – Format Datetime in words

To use TimeHelper you have to enable it first. To enable a helper in your view, add the name of the helper to the controller’s $helpers array:

class MyController extends AppController
    public $helpers = ['Time'];

Each helper is exposed as a public property in the view. Inside your file, for ex. index.ctp, to format a datetime such as, 2015-06-05 14:00:00, into a phrase expressing the relative time using the function timeAgoInWords, do the following:

$TimeAgoInWords = $this->Time->timeAgoInWords('2015-06-09 14:00:00', [
	'format' => 'dd/MM/YYYY', 
	'accuracy' => 'hour', 
	'end' => '1 year'
//Outputs 3 hours ago

The end option lets you define at which point after which relative times should be formatted using the format option. The accuracy option lets us control what level of detail should be used for each interval range.

Categories: CakePHP, PHP Tags: , , ,
%d bloggers like this: