How to Get Current Date Time in CodeIgniter | Date Helper

Hi! This tutorial shows you how to get current date time in codeigniter. During website/application development you'll need to retrieve current date and time in places where you want to keep track of site users last logon date-time or the last modified date of user profile or avatar images.

Since CodeIgniter is a PHP framework, it accepts native PHP code without trouble. So you can use PHP's core date() & time() functions to get current date time in codeigniter.


<?php echo @date('Y-m-d H:i:s'); ?>

But codeignitor comes with its own Date Helper file to deal with dates. And using this helper has certain advantages over PHP date() function.

get-current-date-time-in-codeigniter

Load Date Helper in CodeIgniter:

In order to use codeigniter Date helper functions, you have to load the helper first.


$this->load->helper('date');

CodeIgniter: Get Current Date Time

To get current date time you have to use the function mdate() in codeigniter. This function is similar to PHP date() but allows you to use MySQL style date codes (%Y, %m, %d). So you don't have to escape it while processing the date.

Usage:


$format = "%Y-%m-%d %h:%i %A";
echo mdate($format);

// output:
2016-10-06 05:12 PM

Here's another one example to get the date time in 24 hours format.


$format = "%Y-%M-%d %H:%i";
echo mdate($format);

// output:
// 2016-Oct-06 17:12

And this is the controller demo with function to print the current date time in codeigniter.


<?php
class dateDemo extends CI_Controller
{
function __construct()
{
parent::__construct();
$this->load->helper('url');
}

function index()
{
$this->getDateTime();
}

function getDateTime()
{
//load date helper
$this->load->helper('date');

$format = "%Y-%m-%d %h:%i %a";
echo @mdate($format);
}
}
?>

Read Also: Upload Multiple Images in CodeIgniter Example

Don't Miss: How to Create & Destroy Session in CodeIgniter

That explains about retrieving current date time in php code igniter. Alternatively you can use now() function to get system date & time.

0 Response to "How to Get Current Date Time in CodeIgniter | Date Helper"

Posting Komentar