简体   繁体   中英

Query just day month year from now()

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.

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

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.

$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

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.

另一个选择是使用* date_format *函数直接在SQL中执行此操作: http : //dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM