pixeltocode
pixeltocode

Reputation: 5288

retrieve current date and time in Codeigniter

How can I retrieve the current date and time within a view in Codeigniter?

Thanks.

EDIT : What I'm trying to do is to subtract the current date/time from posted date/time and display it as "posted x days ago"

Upvotes: 0

Views: 9212

Answers (3)

Hilarius L. Doren
Hilarius L. Doren

Reputation: 757

you can do like this

$d1 = new DateTime("2013-07-31 10:29:00");
$d2 = new DateTime("2013-08-02 5:32:12");
echo $d1->diff($d2)->days;

Upvotes: 0

Matthew
Matthew

Reputation: 15662

I use this helper for Codeigniter (you can see the original here: codeigniter forums)

I use this code:

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

if( ! function_exists('relative_time'))
{
    function relative_time($datetime)
    {
        if(!$datetime)
        {
            return "no data";
        }

        if(!is_numeric($datetime))
        {
            $val = explode(" ",$datetime);
            $date = explode("-",$val[0]);
            $time = explode(":",$val[1]);
            $datetime = mktime($time[0],$time[1],$time[2],$date[1],$date[2],$date[0]);
        }

        $difference = time() - $datetime;
        $periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");
        $lengths = array("60","60","24","7","4.35","12","10");

        if ($difference > 0)
        {
            $ending = 'ago';
        }
        else
        {
            $difference = -$difference;
            $ending = 'to go';
        }
        for($j = 0; $difference >= $lengths[$j]; $j++)
        {
            $difference /= $lengths[$j];
        }
        $difference = round($difference);

        if($difference != 1)
        {
            $period = strtolower($periods[$j].'s');
        } else {
            $period = strtolower($periods[$j]);
        }

        return "$difference $period $ending";
    }


}

I'm not sure if you'd always want it to say "days", this code does whatever is least (like '49 seconds ago', or '17 minutes ago', or '6 hours ago', or '10 days ago', or weeks or months (or even years). If what you're looking for is only the days, it'd be easy enough to alter this script.

Upvotes: 3

vikmalhotra
vikmalhotra

Reputation: 10071

You can use simple php function date for that...

<?php echo date("F j, Y, g:i a"); ?>

Upvotes: 0

Related Questions