Displaying 2 digit minutes/seconds
| From: | sono-io at fannullone dot us | Date: | Thu, 20 Aug 2009 21:27:06 +0000 |
| Subject: | Displaying 2 digit minutes/seconds | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-297040@lists.php.net to get a copy of this message | ||
Hi all,
I'm using this code to display the current time for our location on our website:
<?php
date_default_timezone_set('America/Los_Angeles');
$theTimeIs = getdate(time());
$theHour = $theTimeIs['hours'];
$theMinute = $theTimeIs['minutes']; // make minutes under 10 show two digits
$theSecond = $theTimeIs['seconds'];
if($theHour > 12){
$theHour = $theHour - 12;
$dn = "PM";
} else {
$dn = "AM";
}
echo "$theHour:$theMinute:$theSecond $dn";
?>
It works great except for one small detail. If the time is 3:04:02, it is displayed as 3:4:2 which, of course, is very odd looking. So I corrected it as follows:
<?php
date_default_timezone_set('America/Los_Angeles');
$theTimeIs = getdate(time());
$theHour = $theTimeIs['hours'];
if (strlen ($theTimeIs['minutes']) < 2) {
$theMinute = "0" . $theTimeIs['minutes'];
} else {
$theMinute = $theTimeIs['minutes'];
}
if (strlen ($theTimeIs['seconds']) < 2) {
$theSecond = "0" . $theTimeIs['seconds'];
} else {
$theSecond = $theTimeIs['seconds'];
}
if($theHour > 12){
$theHour = $theHour - 12;
$dn = "PM";
} else {
$dn = "AM";
}
echo "$theHour:$theMinute:$theSecond $dn";
?>
It works, but is there a better way to do it?
Thanks,
Frank