on Tips

How to format database dates in PHP

3 comments
calendar
Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon

To format the DATETIME field taken from the database, you have to turn it into a timestamp.

The DATETIME that comes from your query is actually a string. So, to format it, just use strtotime PHP function:

$sql = "SELECT date FROM table WHERE id = " . $id;
$row = db->select_single($sql); // just an example
$date = $row['date'];
echo date("d.m.Y H:i:s", strtotime($date));

Many times people have problems with formating dates with PHP, but when you get the grip, it really is easy.

Tweet about this on TwitterShare on FacebookShare on Google+Share on LinkedInShare on RedditShare on StumbleUpon



  • exdesignorama

    Maybe it would be easier to format date directly in sql query, like this: DATE_FORMAT(date, ‘%d.%m.%Y %H:%i:%s’) AS date,

    • Zvonko

      @exdesignorama I agree with you, but what if you need a few different formats?

  • Zvonko

    @exdesignorama I agree with you, but what if you need a few different formats?