Reputation: 35
I am inserting a date into a database with NOW()
then I query the result. Here is the code.
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;
The
echo '<p>' . $row['date_posted'] . '</p>';
is where I echo the date. When I echo this from the database I get 2012-07-25 19:00:46, because that's what is in the database. My question is how would I echo the day, then echo the month, then the year. Ideally these would all be separate echos so I could style each differently.
Upvotes: 0
Views: 325
Reputation: 2113
This is alot more handy and less code.
$date = new DateTime($row['date_posted']);
$day = date->format('d');
$month = date->format('F');
$year = date->format('Y');
Resource: http://www.php.net/manual/en/class.datetime.php
Upvotes: 2
Reputation: 1482
Another option is to do that directly in SQL, using the *date_format* function: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
Upvotes: 0
Reputation: 4216
You would use php
built in date()
function: 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>
This can be modified into just about any format that you would like.
Upvotes: 0
Reputation: 324650
Since the format is known, you can simply use this:
list($year,$month,$day) = explode("-",substr($row['date_posted'],0,10));
Then you can echo those variables however you want.
Upvotes: 1
Reputation: 6122
$date = strtotime($row['date_posted'];
echo date('d', $date);
echo date('m', $date);
echo date('Y', $date);
or
$date = new DateTime($row['date_posted']);
echo $date->format('Y');
etc
Upvotes: 0