1

I am really new to Codeigniter, and just learning from scratch. I use CI3.

in native PHP I have a function like this ( to calculate the number of days between two dates) :

function dateDiff($date1, $date2){
$d1 = date_create($date1); $d2 = date_create($date2);
$diff = date_diff($d1,$d2);
$result =  $diff->format("%a");
return $result;
}

I have read the manual of CI3 & tried but no success.

this is my trial code

defined('BASEPATH') OR exit('No direct script access allowed');



class DateDiff { 
public $date1 = ''; public $date2 = '';
public function __construct($params)
{
    $d1 = date_create($this->date1); $d2 = date_create($this->date2);
    $diff = date_diff($d1,$d2);
    $result =  $diff->format("%a");
    return $result;
} }

then I call it in other controller, like this :

$NumberOfDays = $this->load->library('datediff', ['2025-01-01','2025-02-02']); echo $NumberOfDays;

Got error.

how to create such a function in CI3 custom library so I can call it in every controller

2
  • Include the error message please. Commented Sep 3 at 8:36
  • Can you elaborate on what the error was? Commented Sep 3 at 10:21

1 Answer 1

3

Since it's a loose function, I would put it in a helper file. Each helper file is simply a collection of functions in a particular category. See the documentation here: https://codeigniter.com/userguide3/general/helpers.html

You could create a standalone helper file, but since it's a date function and CodeIgniter already has a date_helper.php file, I would "extend" their date_helper with your custom function.

Create your own MY_date_helper.php file in /application/helpers/, this "extends" the CodeIgniter date_helper.php file that is in /system/helpers/. Then add your function to the MY_date_helper.php file:

<?php
defined('BASEPATH') or exit('No direct script access allowed');

if (! function_exists('dateDiff')) {
    function dateDiff($date1, $date2)
    {
        $d1 = date_create($date1);
        $d2 = date_create($date2);
        $diff = date_diff($d1, $d2);
        $result =  $diff->format("%a");
        return $result;
    }
}

You can then use it in your controller like you would any other helper:

$this->load->helper('date');
$NumberOfDays = dateDiff('2025-01-01','2025-02-02');
echo $NumberOfDays;
Sign up to request clarification or add additional context in comments.

1 Comment

I agree with @Marleen, but in general if you want to create your own library, you can see the documentation codeigniter.com/userguide3/general/creating_libraries.html

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.