来自 mysql 数据库的回显日期时间
Echo Datetime from mysql database
我的数据库中有一个日期时间类型的字段,在插入记录时使用 CURRENT_TIME
填充该字段。
它看起来像:2015-01-05 19:07:03
我的问题是在查询数据库时如何获取它并将其格式化为字符串以便我可以通过 php 回显它。
我当前的代码:
$testssql="SELECT * FROM LogTest WHERE DriverID = '$userid' AND Complete = '1'";
$testsresult=mysqli_query($conn, $testssql);
while($row = mysqli_fetch_array($testsresult))
{
date('l, F d, Y', strtotime($row['Date']));
}
但是这不管用 $row['Date']
使用PHP的DateTime class:
$date = DateTime::createFromFormat('Y-m-d H:i:s', $row['Date']);
echo $date->format('Y-m-d'); // Change format as needed
编辑:
您应该能够使用 try/catch 块追踪错误:
try {
$date = new DateTime($row['Date']);
echo $date->format('Y-m-d'); // Change format as needed
} catch (Exception $e) {
echo $e->getMessage();
exit(1);
}
干杯!
我的数据库中有一个日期时间类型的字段,在插入记录时使用 CURRENT_TIME
填充该字段。
它看起来像:2015-01-05 19:07:03
我的问题是在查询数据库时如何获取它并将其格式化为字符串以便我可以通过 php 回显它。
我当前的代码:
$testssql="SELECT * FROM LogTest WHERE DriverID = '$userid' AND Complete = '1'";
$testsresult=mysqli_query($conn, $testssql);
while($row = mysqli_fetch_array($testsresult))
{
date('l, F d, Y', strtotime($row['Date']));
}
但是这不管用 $row['Date']
使用PHP的DateTime class:
$date = DateTime::createFromFormat('Y-m-d H:i:s', $row['Date']);
echo $date->format('Y-m-d'); // Change format as needed
编辑:
您应该能够使用 try/catch 块追踪错误:
try {
$date = new DateTime($row['Date']);
echo $date->format('Y-m-d'); // Change format as needed
} catch (Exception $e) {
echo $e->getMessage();
exit(1);
}
干杯!