PHP Time formatting

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
noon
Forum Newbie
Posts: 5
Joined: Tue Nov 21, 2006 12:16 pm

PHP Time formatting

Post by noon »

Hi,

I'm receiving a string that comes in the format of "9:4". Leading zeroes are not printed on the hour format. Trailing zeroes are not shown either. echo'ing the string is only good when the minute does not end in a 0, since it doesn't show. I tried using:

Code: Select all

<?php echo date_format($weather[0], "g:i"); ?>
Where weather[0] is equal to 9:4. I'm sure this wouldn't work, but I thought I would try before I came here anyways. Is there way to convert 9:4 to a date object somehow?

Thanks!
User avatar
Jaxolotl
Forum Contributor
Posts: 137
Joined: Mon Nov 13, 2006 4:19 am
Location: Argentina and Italy

try this

Post by Jaxolotl »

try this

Code: Select all

function add_zero($string){
	$string = explode(":",$string);
	foreach($string as $key => $val){
		if(strlen($string[$key])<2){
			$string[$key] = "0".$string[$key];
		}
	}
	return implode(":",$string);
}
echo add_zero($weather[0]);
this this script add you the 0 before the number but to complete it you'd have to tell if 9:4 means 9 hours 4 minutes or 9 minutes 4 seconds, and explain if the time format you need is 00:00:00.....adn if the time format you need is in 24 format or 12 am/pm format
noon
Forum Newbie
Posts: 5
Joined: Tue Nov 21, 2006 12:16 pm

Post by noon »

Thanks a lot for the help. Let me explain it a little better though. 9:4 actually means 9:40. And I was looking to display it in 12hr ampm format. 9:40am. Thanks
noon
Forum Newbie
Posts: 5
Joined: Tue Nov 21, 2006 12:16 pm

Post by noon »

I realized that ampm format wouldn't be possible unless the string I received was in 24 hour format. Anyways, I changed the code around a bit and it works to suit my needs now.

Code: Select all

function add_zero($string)
{
$string = explode(":",$string);
if(strlen($string[1])<2)
	{
	$string[1] = $string[1]."0";
    }
return implode(":",$string);
}
Thanks for the start though
User avatar
RobertGonzalez
Site Administrator
Posts: 14293
Joined: Tue Sep 09, 2003 6:04 pm
Location: Fremont, CA, USA

Post by RobertGonzalez »

Where is the string being set to 9:4? Is there a way that this can be corrected so you don't have to manipulate a bunch of stuff with code?
Post Reply