Re: Displaying 2 digit minutes/seconds

From: Date: Thu, 20 Aug 2009 21:34:52 +0000
Subject: Re: Displaying 2 digit minutes/seconds
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-297041@lists.php.net to get a copy of this message
You can use sprintf or str_pad to fill in with zeros, with sprintf you can do this: echo sprintf('%02d', 5); That will print the string "05". Jonathan On Thu, Aug 20, 2009 at 6:27 PM, <sono-io@fannullone.us> wrote: > 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 > > -- > PHP General Mailing List (http://www.php.net/) > To unsubscribe, visit: http://www.php.net/unsub.php > >

« previous php.general (#297041) next »