如何使用php将日期差的结果插入mysql数据库?

iibxawm4  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(366)
<?php
    function find_days($start_date, $end_date) {
    $response = new stdClass();
    try {
    $sdate = new DateTime($start_date);
    $edate = new DateTime($end_date);
    $dateInterval = $edate->diff($sdate);
    $response->status = true;
    $response->result = $dateInterval;
    return $response;
    } catch (Exception $e) {
    $response->status = false;
    $response->result = 'Invalid Date Format';
    return $response;
    }
    } 
    ?>            
    Start Date: <input type="date" name="sdate" placeholder="start date" /> 
    End Date: <input type="date" name="edate" placeholder="end date" /> 
    <input type="submit" value="Find Days" />
    <?php
           if (isset($_POST['sdate']) && $_POST['sdate']) {
            $start_date = $_POST['sdate'];
            $end_date = $_POST['edate'];
            //now call the function
            $days_array = find_days($start_date, $end_date);
            if ($days_array->status) {
            echo " <input  type='text' name='day' 
            value='.$days_array>result>days.' />";
            $day = $_POST['day'];                   
            $query   = "INSERT into cart (date,edate,days) 
            VALUES('$start_date','$end_date','$day')";
            $success = $conn->query($query);
            if (!$success) {
            die("Couldn't enter data: ".$conn->error);  
            }
            } else {
                echo $days_array->result;
            }
        }

我的代码运行得很好。但结果只显示在屏幕上。因此,我尝试将结果存储在文本框中,然后以通常的方式插入到表中。但是我在第45行遇到了一个错误“catchable fatal error:dateinterval类的对象无法转换为c:\xampp\htdocs\date.php中的字符串”,我不知道如何纠正这个错误。。请帮我解决这个问题。

0x6upsns

0x6upsns1#

必须使用以下格式将其转换为字符串:

<?php
$now = new DateTime();
$hour = new DateTime( "now +1hours +13minutes +22seconds" );
$diff = $now->diff( $hour );

echo $now->format('Y-m-d H:i:s');
echo "\n";
echo $hour->format('Y-m-d H:i:s');
echo "\n";
echo $diff->format('%H:%I:%S');

输出

2018-07-26 20:53:42
2018-07-26 22:07:04
01:13:22

相关问题