Carbon Date Time library usage with CodeIgniter
CodeIgniter App setup:
First let me give you an introduction about my CodeIgniter project setup on the localhost is as follows:
/
|- gheapp
| |- application
| |- system
| L- vendor
| | |-bin
| | |-composer
| | |-nesbot/carbon
| | |-symfony
| |
| |----- composer.json
| L----- composer.lock
|
|- public_html
| |- .htaccess
| L- index.php
And in the index.php
I have set up the following paths to the system and the application:
$system_path = '../gheapp/system';
$application_folder = '../gheapp/application';
Note 1: by doing so, our application source code becomes hidden to the public at first.
Note 2: For more nitty-gritty about my CodeIgniter setup please follow the following StackOverflow Answer of mine
Step 1: how do I fetch the Carbon package.
Using Composer I fetched the Cabron
package to my CodeIgniter App. My composer.json
looks like following (it's simplified for your ease).
{
"require": {
"nesbot/carbon": "^1.22"
}
}
After you run composer command composer install
it creates the vendor
folder within your CI app root and puts the Carbon package as shown above in the folder structure.
Step 2: Autoload Composer downloaded Packages:
In my index.php
before the line at the bottom
require_once BASEPATH.'core/CodeIgniter.php';
I have put the following two lines:
$composer_vendor_path = '../gheapp/vendor';
require_once $composer_vendor_path.'/autoload.php';
So now my CodeIgniter
app knows how and where to load the composer installed Packages.
Step 3: how do I use the Carbon package within my controller:
Within any method function of my controller (or model) I can use Carbon
as follows:
$date = Carbon\Carbon::today();
echo $date; // output: 2017-01-21 00:00:00
echo '<br/>'.$date->diffForHumans(); // output: 7 hours ago
For further details about using Carbon please visit the following link: Carbon from nesBot
I hope my answer will be useful/helpful to somebody else out there in the future! :-)