我使用NOW()
将日期插入数据库,然后查询结果。这是代码。
function get_content($id = ''){
if($id != ''):
$id = mysql_real_escape_string($id);
$sql = "SELECT * FROM cms_content WHERE id = '$id'";
$return = '<p><a href="index.php">Back to Content</a></p>';
else:
$sql = "SELECT * FROM cms_content ORDER BY id DESC";
endif;
$res = mysql_query($sql) or die(mysql_error());
if(mysql_num_rows($res) != 0):
while($row = mysql_fetch_assoc($res)) {
echo '<h1><a href="index.php?id=' . $row['id'] . ' "> ' . $row['title'] . '</a></h1>';
echo '<p>' . stripslashes($row['body']) . '</p>';
**echo '<p>' . $row['date_posted'] . '</p>';**
}
else:
echo '<p> You broke it!, this post dosn't exsist!';
endif;
echo $return;
echo '<p>' . $row['date_posted'] . '</p>';
是我呼应日期的地方。当我从数据库中回显这个时,我会得到2012-07-25 19:00:46,因为这就是数据库中的内容。我的问题是,我该如何回应日期,然后回应月份,然后回应年份。理想情况下,这些都是单独的回声,这样我就可以对每个回声进行不同的风格设计。
这更方便,代码更少。
$date = new DateTime($row['date_posted']);
$day = date->format('d');
$month = date->format('F');
$year = date->format('Y');
资源:http://www.php.net/manual/en/class.datetime.php
由于格式已知,您可以简单地使用以下内容:
list($year,$month,$day) = explode("-",substr($row['date_posted'],0,10));
然后,您可以随心所欲地回显这些变量。
$date = strtotime($row['date_posted'];
echo date('d', $date);
echo date('m', $date);
echo date('Y', $date);
或
$date = new DateTime($row['date_posted']);
echo $date->format('Y');
etc
您将使用date()
函数中内置的php
:http://us.php.net/manual/en/function.date.php
echo "<p>".date('j M, Y', $row['date_posted'])."</p>";
// would output <p>25 July, 2012</p>
这可以被修改成你想要的任何格式。
另一个选项是使用*date_format*函数直接在SQL中执行此操作:http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-格式化