我想使用输入日期(2018-12-05)将其转换为时间戳格式(2018-12-05 00:00:00),以便可以将此时间戳与我的数据库时间戳进行比较。这样做吗?
我尝试按照代码中的说明转换日期格式,但出现此错误。
<table class="table table-borderless table-data3">
<h3>Expense Table</h3>
<br>
<thead>
<tr>
<th>Title</th>
<th>Amount</th>
<th>Amount</th>
</tr>
</thead>
<tbody>
<?php
if(isset($_POST['submit'])){
$connect = new PDO("mysql:host=localhost;dbname=inventory_management_system", "root", "");
//get input in date format like 2018-12-05
$start_date=$_POST['start_date'];
$end_date=$_POST['end_date'];
$time = new DateTime('00:00:00');
//convert date to timestamp format like 2018-12-05 00:00:00
$date1 = new DateTime($start_date);
$sdate = new DateTime($date1->format('Y-m-d') .' ' .$time->format('H:i:s'));
$strDate = $sdate->format('Y-m-d H:i:s'); // Outputs like '2017-03-14 00:00:00'
$date2 = new DateTime($end_date);
$edate = new DateTime($date2->format('Y-m-d') .' ' .$time->format('H:i:s'));
$endDate = $edate->format('Y-m-d H:i:s'); // Outputs like '2017-03-14 00:00:00''
//get data between the two converted date $sdate and $edate
$query='select amount,date from pl_per_day where STR_TO_DATE(date,"%Y-%m-%d %T")>=STR_TO_DATE($strDate,"%Y-%m-%d") AND STR_TO_DATE(date,"%Y-%m-%d %T")<=STR_TO_DATE($endDate,"%Y-%m-%d")';
$query_run=mysqli_query($connect , $query);
while($row=mysqli_fetch_array($query_run))
{
$moddate=strtotime($row['date']);
?>
<tr>
<td><?php echo $amount; ?></td>
<td><?php echo $moddate; ?></td>
<?php } } ?>
</tr>
</tbody>
答案 0 :(得分:-1)
在您的PHP脚本中,$ sdate和$ edate是DateTime类的对象。 您应该从如下对象中获取字符串值; -您的代码
$sdate = new DateTime($date1->format('Y-m-d') .' ' .$time->format('H:i:s'));
$sdate->format('Y-m-d H:i:s'); // Outputs like '2017-03-14 00:00:00'
修复
$sdate = new DateTime($date1->format('Y-m-d') .' ' .$time->format('H:i:s'));
$strDate = $sdate->format('Y-m-d H:i:s'); // Outputs like '2017-03-14 00:00:00'
如果“ format”方法由于某种原因失败,它将返回FALSE,因此需要进行检查。
if (!$strDate) {
$strDate = '1900-01-01 00:00:00';
}
答案 1 :(得分:-1)
$start_date = $_POST['start_date'];
$end_date = $_POST['end_date'];
$sdate = new DateTime($start_date . ' 00:00:00');
$edate = new DateTime($end_date . ' 23:59:59');
$query = sprintf("select amount,date from pl_per_day where date between '%s' and '%s'",
$sdate->format('Y-m-d H:i:s'),
$edate->format('Y-m-d H:i:s')
);
答案 2 :(得分:-2)
您可以在查询本身中进行所有转换,如下所示。如果还需要时间比较,则可能必须将H:I:S部分添加到查询的$input = $mysqli->real_escape_string($_POST['input']);
$sqlcheck = "SELECT * FROM questions WHERE word LIKE '%".$input."%' AND id = $pos";
$sqlresult = mysqli_query($mysqli, $sqlcheck);
和$sdate
中。
$edate