Re: Displaying 2 digit minutes/seconds

From: Date: Thu, 20 Aug 2009 21:38:40 +0000
Subject: Re: Displaying 2 digit minutes/seconds
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-297042@lists.php.net to get a copy of this message
On Thu, 2009-08-20 at 14:27 -0700, 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 > What's wrong with using the date() function? You can have it output any sort of format you wish. So, getting a 2 digit time in hours:minutes:seconds you would put: date("H:i:s"); Thanks, Ash http://www.ashleysheridan.co.uk

« previous php.general (#297042) next »