Last Updated: February 25, 2016
· euantor

Using PHP to output a valid timestamp for use with <time>

I've been using the new HTML5 <time> element in a lot of my applications for a while now and have always just been using date() to format the output into the required form ("YYYY-MM-DDTHH:MM::SSTimezone"). Which, obviously, is fairly long winded. Today though, I noticed for the first time that PHP 5 introduced a new time formatter in the form of "c" that returns a perfect ISO date which can be used with the <time> tag. I have no idea how I never knew about it till now, but there we go.

Therefore, to output a valid date for use with <time> from a MySQL datetime column in PHP, one can simply do this:

$date = strotime($data['date']);
$isoDate = date('c', $date);
$humanDate = date('D \t\h\e jS \of F, Y \a\t h:iA', $date);

Then use the following in your view file:

<time datetime="{$isoDate}">{$humanDate}</time>

Easy, eh? Now all we need to wait for is for browsers to make better use of the <time> tag...