0

I'm creating a ticketsystem and now I'm trying to echo the age of a ticket. The ticket date/time is stored in the DB as a timestamp. I found this code:

function time_elapsed_string($datetime, $full = false) {
    $now = new DateTime;
    $ago = new DateTime($datetime);
    $diff = $now->diff($ago);

    $diff->w = floor($diff->d / 7);
    $diff->d -= $diff->w * 7;

    $string = array(
        'y' => 'year',
        'm' => 'month',
        'w' => 'week',
        'd' => 'day',
        'h' => 'hour',
        'i' => 'minute',
        's' => 'second',
    );
    foreach ($string as $k => &$v) {
        if ($diff->$k) {
            $v = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
        } else {
            unset($string[$k]);
        }
    }

    if (!$full) $string = array_slice($string, 0, 1);
    return $string ? implode(', ', $string) . ' ago' : 'just now';
}

On this page: Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...

And I'm talking about Glavić's answer. He says:

Output:
4 months ago
4 months, 2 weeks, 3 days, 1 hour, 49 minutes, 15 seconds ago

But the only output I get is 3 days, or 1 hour. The output I need is:

Only minutes old: 45 minutes
Hours and minutes old: 2 hours 22 minutes
Days, hours and minutes old: 3 days 3 hours (don't show the minutes)

And when it's older than a month or year it should keep echo'ing it in days like: 45 days 22 hours or 586 days 4 hours

Is this possible? I really hope my question is clear enough and thanks for any help!

Community
  • 1
  • 1
Cris Kolkman
  • 165
  • 2
  • 10

2 Answers2

4

If you create Datetime objects, you could use the diff() function to achieve this:

$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
echo "difference " . $interval->y . " years, " . $interval->m." months, ".$interval->d." days "; 

// shows the total amount of days (not divided into years, months and days like above)
echo "difference " . $interval->days . " days ";

If you var_dump($difference) you should get something like:

object(DateInterval)
  public 'y' => int 0
  public 'm' => int 0
  public 'd' => int 20
  public 'h' => int 6
  public 'i' => int 56
  public 's' => int 30
  public 'invert' => int 0
  public 'days' => int 20
Naruto
  • 1,210
  • 3
  • 25
  • 28
0

Code I'm using now:

function time_elapsed_string($ptime){
        $date1 = new DateTime(date("Y-m-d H:i", $ptime));
        $date2 = new DateTime(date("Y-m-d H:i", time()));
        $interval = $date1->diff($date2);
        if($interval->days > 0){ $result = $interval->days . ' d ';$result .= $interval->h . ' u '; } else { $result = $interval->h . ' u '; }
        if(($interval->days < 1) && ($interval->h < 1)){ $result = $interval->i . ' m'; } else { $result .= $interval->i . ' m'; }
        return $result;
    }
Cris Kolkman
  • 165
  • 2
  • 10