Reputation: 26281
How do I display the time only if it is not 00:00:00
? This works, however, I question whether there is a less cryptic way of doing so. Note that the datetimes provided will be standard MySQL datetime data types, and the desired datetimes to be displayed will vary. Thanks
<?php
function formatDate($d)
{
$f='Y-m-d'.((strlen($d)==19 && substr($d, -8)!='00:00:00')?' H:i:s':null);
$date = new DateTime($d);
return $date->format($f);
}
echo(formatDate("2014-11-02 02:04:05").'<br>');
echo(formatDate("2014-11-02 00:00:00").'<br>');
?>
Upvotes: 0
Views: 4658
Reputation: 7447
Your method seems fine, but you could also do this:
$f = 'Y-m-d' . (date('H:i:s', strtotime($d)) != '00:00:00' ? ' H:i:s' : '');
Update:
@zerkms makes a great point in his comment. Why reformat into the same format? Unless you are going to use a different format than Y-m-d
, then you might be better served not using a function at all, and just using str_replace()
. Or you could simplify your function as such:
function formatDate($d)
{
return str_replace(' 00:00:00', '', $d);
}
Upvotes: 2