我使用以下脚本将日历信息从mysql数据库中提取出来并显示在页面上。我试图从标准的Mysql日期格式重新格式化日期,但是从数据库中检索它时会出现以下错误:
Warning: date_format() expects parameter 1 to be DateTime, string given in C:\easyphp\www\twinfocus\managecalendar.php on line 24
Warning: date_format() expects parameter 1 to be DateTime, string given in C:\easyphp\www\twinfocus\managecalendar.php on line 24
Warning: date_format() expects parameter 1 to be DateTime, string given in C:\easyphp\www\twinfocus\managecalendar.php on line 24
Warning: date_format() expects parameter 1 to be DateTime, string given in C:\easyphp\www\twinfocus\managecalendar.php on line 24
数据库(如您所见,日期存储正确):
剧本:
<?php
$sql2 = <<<SQL
SELECT *
FROM `calendar`
SQL;
if(!$result2 = $db->query($sql2)){ die('There was an error running the query [' . $db->error . ']');}
echo '<table class="admintable"> <thead>';
echo '<tr><th>Client Names</th><th>Email</th><th>Tel</th><th>Wedding Date</th><th>Date Created</th><th>Start Time</th><th>End Time</th><th>Price</th><th>Location</th><th>Other Info</th><th>Edit</th><th>Delete</th></tr></thead>';
while($row2 = $result2->fetch_assoc()){
$weddingdate = $row2['weddingdate'];
$formattedweddingdate = date_format($weddingdate, 'd-m-Y');
echo '<tr><td>'.$row2['name'].'</td><td>'.$row2['email'].'</td><td>'.$row2['tel'].'</td><td style="min-width:70px;">'.$formattedweddingdate.'</td><td style="min-width:70px;">'.$row2['datecreated'].'</td><td>'.$row2['starttime'].'</td><td>'.$row2['endtime'].'</td><td>£'.$row2['price'].'</td><td>'.$row2['location'].'</td><td style="min-width:400px;">'.$row2['otherinfo'].'</td><td><a href="managecalendar.php?&key='.$key.'&editwedding='.$row2['id'].'">Edit</a></td><td><a href="calenderdelete.php?&key='.$key.'&delwedding='.$row2['id'].'">Delete</a></td></tr>';}
echo '</table>';
?>
答案 0 :(得分:22)
最好的方法是使用DateTime对象来转换您的日期。
$myDateTime = DateTime::createFromFormat('Y-m-d', $weddingdate);
$formattedweddingdate = $myDateTime->format('d-m-Y');
注意:它仅支持PHP 5&gt; = 5.3.0。
答案 1 :(得分:16)
您需要将DateTime对象传递给此func。 见手册: php
string date_format ( DateTime $object , string $format )
您可以尝试使用:
date_format (new DateTime($time), 'd-m-Y');
或者您也可以使用:
$date = date_create('2000-01-01');
echo date_format($date, 'Y-m-d H:i:s');
答案 2 :(得分:12)
你为什么不这样试试呢?
$Weddingdate = new DateTime($row2['weddingdate']);
$formattedweddingdate = date_format($Weddingdate, 'd-m-Y');
或者您也可以这样做:
$Weddingdate = new DateTime($row2['weddingdate']);
echo $Weddingdate->format('d-m-Y');
答案 3 :(得分:2)
这可能会帮助
$formattedweddingdate =date('d-m-Y',strtotime($weddingdate));
答案 4 :(得分:1)
尝试
$start_date = date_create($_POST['start_date']);
$start_date = date_format($start_date,"Y-m-d H:i:s");
答案 5 :(得分:0)
我已经尝试过sean662的第3个解决方案,并使用存储在INSERT sql中的now()函数和date_create()函数中的值。之后,变量将通过date_format()函数传递,您可以拥有自己喜欢的日期顺序。