簡體   English   中英

如何在 php 和 mysql 中使用日期?

[英]How can I work with date in php and mysql?

我想知道如何處理 MySQL 和 PHP 中的日期。 我想知道還有多少天,我想知道 nowTime 和 createTime 之間的差異(距離)是多少天?

<?php
    $response = array();

    // include db connect class
    require_once __DIR__ . '/db_connect.php';

    // connecting to db
    $db = new DB_CONNECT();

    ////ISSET
    if (isset($_POST['projectId'])) {
        $projectId = $_POST['projectId'];

        $result = mysql_query("SELECT *FROM projects WHERE projectId='$projectId'") ;
        if (mysql_num_rows($result)>0) {
            $result = mysql_fetch_array($result);

            $response["title"]=$result["title"];
            $response["exp"]=$result["exp"];
            $response["userIdKarmand"]=$result["userIdKarmand"];
            $response["userIdKarfarma"]=$result["userIdKarfarma"];
            $response["cost"]=$result["cost"];
            $response["zemanat"]=$result["zemanat"];
            $response["time"]=$result["time"];
            $response["createTime"]=$result["createTime"];
            $response["type"]=$result["type"]; 
            $response["nowTime"]=DATE("y-m-d");
            $response["remainTime"]=DATE("y-m-d")-    strtotime($response["createTime"])+$response["time"];
            echo json_encode($response);
        } 
        else {
        }
    }
    else {
   }
?>

它不起作用。 我能做什么? 我想比較createtimenowtime並找出我有多少天的時間?

strtotime 將格式化的字符串日期格式轉換為時間戳。 您不能從字符串數據中減去時間戳數據。 您必須首先使用 strtotime() 將 $response["remainTime"] 轉換為時間戳,然后從此值中減去 strtotime($response["createTime"]) 。

查看 MySQL 結果的最佳方法是循環遍歷fetch_assoc()函數。

$result = mysql_query("SELECT * FROM projects WHERE projectId = '$projectId'");

// while() through an associative array from the MySQL object
while($result =& $result->fetch_assoc()) {
    $response["title"]                = $result["title"];
    $response["exp"]                  = $result["exp"];
    $response["userIdKarmand"]        = $result["userIdKarmand"];
    $response["userIdKarfarma"]       = $result["userIdKarfarma"];
    $response["cost"]                 = $result["cost"];
    $response["zemanat"]              = $result["zemanat"];
    $response["time"]                 = $result["time"];
    $response["createTime"]           = $result["createTime"];
    $response["type"]                 = $result["type"];
    $response["nowTime"]              = DATE("Y-m-d H:i:s"); // this is how you would need to format dates to work with MySQL
    $remainTime = (strtotime($response['nowTime']) - strtotime($response['createTime'])); // this would return how many seconds have passed since $response['createTime'] until now
    $response["remainTime"]           = $remainTime;
 }
echo json_encode($response);

這將允許您在$remainTime變量中保存自$response['createTime']以來的$remainTime

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM