CakePHP Calculate Days


CakePHP are able to calculate total days based on date input from users by using the standard PHP diff class. Assume there is a table that stored employee leaves and the input is date start and date end for employees’ leaves. So, we going to create a simple calculation process that will calculate the total days of leaves for the employee based on the date input and store the total into ‘days’ column in database. These operation need developers to modify the controller as the calculation need to be done in the controller before stored into database.
The input for this sample is date_start and date_end where date start is the date that the employees start leaves and date_end is the end of the leaves. Here the sample of input:
The sample coding used in these tutorial also capture the user_id that applied for the leaves, so developer need to have a login system first and login before use this function. If developer not create any login function, then neglect the code at line 4 and 5. Here the sample code:
public function add() {
if ($this->request->is('post')) {
$this->request->data['Leafe']['user_id']= //auto request the id (required login)
		//to change array into yyyy-mm-dd for start date
$startstring = $this->request->data['Leafe']['date_start']['year'] . '-' .
		$this->request->data['Leafe']['date_start']['month'] . '-' .
		//to change array into yyyy-mm-dd for end date			   
		$endstring = $this->request->data['Leafe']['date_end']['year'] . '-' .
		$this->request->data['Leafe']['date_end']['month'] . '-' .
	$start = date('Y-m-d', strtotime($startstring));
	$end = date('Y-m-d', strtotime($endstring));
	$start = new DateTime($start);
	$end = new DateTime($end);
//calculate total different days between date input.
	$days = $start->diff($end)->days;
	$this->request->data['Leafe']['days'] = $days;
if ($this->Leafe->save($this->request->data)) {
	$this->Session->setFlash(__('The leafe has been saved.'));
			return $this->redirect(array('action' => 'index'));
	} else {
	$this->Session->setFlash(__('The leafe could not be saved. Please, try again.'));
	$users = $this->Leafe->User->find('list');


The output will store the total days of leaves based on the input. Good luck!
Author Information
Muhammad Asyraf bin Wahi Anuar
Web Administrator
Asyraf enjoys life and has great enthusiasm for all outdoors activities especially MTB! Don't Follow Me. I'm Lost Too -_-

Muhammad Asyraf bin Wahi Anuar | Copyright 2017 | Informatic Trooper