views:

40

answers:

2

Hi,

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"

+1  A: 

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

<?php echo date("F j, Y, g:i a"); ?>
ShiVik
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"
pixeltocode
@pixeltocode - what's the format you're posting the date/time in?
ShiVik
well, i'm not actually posting it it. i just want to retrieve the date from mysql.
pixeltocode
+3  A: 

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.

Matthew
perfect. thanks.
pixeltocode