将日期时间输出更改为“今天”并断开时间

时间:2015-07-23 18:13:05

标签: php mysql datetime

如果我有以下代码,我从我的数据库输出项目。我想知道如何查看是否有与今天相同的日期,然后输出的数据将反响出来'今天'而不是7-23-15,同样适用于昨天'如果我正在看昨天发布的东西。

然后我想知道我是否可以在数据库中断开日期时间条目的时间部分而只回显时间?

我的数据库中有DATETIME作为我的数据类型。

$stmt2 = $con->prepare("SELECT `id`, `category_id`, `topic_id`, `post_creator`, `post_content`, `post_date` FROM forum_posts WHERE `category_id`=? AND `topic_id`=?");
    if($stmt2===false) {
    die();
    } else {
        //var_dump($stmt2);

            $stmt2->bind_param("ii", $cid, $tid);
            $stmt2->execute();
            $stmt2->store_result();
            $stmt2->bind_result($post_id, $post_category_id, $post_topic_id, $post_creator, $post_content, $post_date);
            //$result2 = $stmt2->get_result();
            if (!$stmt2) {
            throw new Exception($con->error);
            }
        }
    $num_rows2 = $stmt2->num_rows;
    if($num_rows2) {
        while($stmt2->fetch()) {
        $post_id;
        $post_category_id;
        $post_topic_id;
        $post_creator;
        $post_content;
        $post_date;

2 个答案:

答案 0 :(得分:1)

替换:

$stmt2 = $con->prepare("SELECT `id`, `category_id`, `topic_id`, `post_creator`, `post_content`, `post_date` FROM forum_posts WHERE `category_id`=? AND `topic_id`=?");

使用:

$stmt2 = $con->prepare("SELECT `id`, `category_id`, `topic_id`, `post_creator`, `post_content`, IF(DATE(`post_date`) = CURDATE(), 'Today', DATE(`post_date`)) FROM forum_posts WHERE `category_id`=? AND `topic_id`=?");

这将仅返回日期部分。如果是当前日期,它将返回'今天'。

答案 1 :(得分:0)

此PHP函数接受Unix时间戳并以您想要的格式返回它:

function fixDate($strDateTime) {

    $strFormat = 'Y-m-d';
    $intTimeStamp = strtotime($strDateTime);
    $strDate = date($strFormat, $intTimeStamp);
    $strTime = date('H:i', $intTimeStamp);

    if($strDate == date($strFormat)) {
        return "Today " . $strTime;
    }
    elseif($strDate == date($strFormat, strtotime('yesterday'))) {
        return "Yesterday " . $strTime;
    }
    else {
        return $strDate . " " . $strTime;
    }

}

现在,当你想要使用你的约会时,比如输入它,而不是

echo $post_date;
你做了

echo fixDate($post_date);

如果您想要的格式不是YYYY-MM-DD,请更改strFormat的值。 PHP文档的相关部分是here