首页 文章

从mysql数据库获取时间戳并获取php以天,小时,分钟计算时间? [重复]

提问于
浏览
-2

可能重复:PHP:格式化时间Stackoverflow或Apple Mail样式

嗨,有人可以帮助我,我回应了mysql表中的时间戳,但我希望php计算时间戳,以天/小时/分钟 .

这是可能的,我仍然是php和mysql的新手,我正在学习,所以有人可以指导我正确的方向或告诉我如何做到这一点 . 谢谢

<? echo "{$news['date_added']}";?>

我希望输出为秒数:添加12秒前或添加3分钟前或添加4天前或添加4个月前

我认为脚本应该是这样的:

function nicetime($date)
{
    if(empty($date)) {
        return "No date provided";
    }

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

    $now             = time();
    $unix_date         = strtotime($date);

       // check validity of date
    if(empty($unix_date)) {   
        return "Bad date";
    }

    // is it future date or past date
    if($now > $unix_date) {   
        $difference     = $now - $unix_date;
        $tense         = "ago";

    } else {
        $difference     = $unix_date - $now;
        $tense         = "from now";
    }

    for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
        $difference /= $lengths[$j];
    }

    $difference = round($difference);

    if($difference != 1) {
        $periods[$j].= "s";
    }

    return "$difference $periods[$j] {$tense}";
}

$date = "{$news['content']}";
$result = nicetime($date); // 2 days ago ?>

3 回答

  • 0
    $datetime1 = new DateTime();
    $datetime2 = new DateTime('2013-02-03 19:13:00');
    $interval = $datetime1->diff($datetime2);
    echo $interval->format('%h hours %i minutes');
    

    See it in action

    参考

  • 2

    请查看手册中的 date() 功能 . http://php.net/manual/en/function.date.php

    <?php echo date("Y-m-d",$news['date_added']); ?>
    

    将打印例如:

    2013-02-04
    
  • 0

    如果您在MySQL表中的时间戳,您可以使用 FROM_UNIXTIME 函数以适当的格式获取它 .

相关问题