计票年龄

时间:2015-08-04 09:52:28

标签: php time

我正在创建一个票证系统,现在我正在尝试回应票证的年龄。 票证日期/时间作为时间戳存储在DB中。 我找到了这段代码:

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';
}

在此页面上:Converting timestamp to time ago in PHP e.g 1 day ago, 2 days ago...

我在谈论格拉维奇的回答。 他说:

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

但我得到的唯一输出是3天,或1小时。 我需要的输出是:

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)

当它超过一个月或一年时,它应该在几天内保持呼应:45天22小时或586天4小时

这可能吗?我真的希望我的问题很清楚,谢谢你的帮助!

2 个答案:

答案 0 :(得分:4)

如果您创建Datetime个对象,可以使用diff()函数来实现此目的:

$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 ";

如果你var_dump($difference),你应该得到类似的东西:

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

答案 1 :(得分:0)

Code I现在使用:

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;
    }