View Full Version : How to CONVERT seconds to minutes?
BuildHome
Oct 27th 2007, 3:17 am
Hello,
I'm an ASP programmer but I have a PHP script but I don't know PHP :o
I have a var that have int value of seconds, such as:
$seconds = "150";
How can I change it to minutes format, like:
150 seconds => 02:30 minutes
I will thank everyone who will be able to help me :rolleyes:
Thanks.
dpfreaks
Oct 27th 2007, 3:24 am
echo floor($seconds/60) . ":" . $seconds % 60;
legend2
Oct 27th 2007, 3:28 am
<?
$seconds = "150";
$minutes = floor($seconds/60);
$secondsleft = $seconds%60;
if($minutes<10)
$minutes = "0" . $minutes;
if($secondsleft<10)
$secondsleft = "0" . $secondsleft;
echo "$minutes:$secondsleft minutes";
?>
krakjoe
Oct 27th 2007, 3:37 am
<?php
function minutes( $seconds )
{
return sprintf( "%02.2d:%02.2d", floor( $seconds / 60 ), $seconds % 60 );
}
echo minutes( 150 );
?>
andrews
Oct 27th 2007, 3:41 am
probably there's a better way...anyway I coded this and works
<?PHP
function secondMinute($seconds){
/// get minutes
$minResult = floor($seconds/60);
/// if minutes is between 0-9, add a "0" --> 00-09
if($minResult < 10){$minResult = 0 . $minResult;}
/// get sec
$secResult = ($seconds/60 - $minResult)*60;
/// if secondes is between 0-9, add a "0" --> 00-09
if($secResult < 10){$secResult = 0 . $secResult;}
/// return result
echo $minResult,":",$secResult;
}
/// print
secondMinute(150);
?>
EDIT: there was no replies when I started to code it eheh, but now there are better ones :-)
BuildHome
Oct 27th 2007, 3:44 am
dpfreaks, thanks but I also wanted "0" before the time if it's lower than 10 minutes.
legend2, that's what I wanted.
You just forgot to add "s" to the "second" var in your second line, I've fixed it and now it's working GREAT!!
krakjoe and andrews, Your code is also what I wanted. Very easy to understand & usage. Thanks!
Thank you all my friends for your quick help!
I've added to each of you a Rep :D
krakjoe
Oct 27th 2007, 3:47 am
If there is a function for something, like formatting strings for instance, you should use it, there is less margin for error when you utilize functions that are tried and tested ... plus it's already been established by programmers far more experienced than yourself ( the php authors ) that this is the optimal way of carrying out a task ...
BuildHome
Oct 27th 2007, 3:49 am
Yes, I'm already using the function that you've wrote :)
vBulletin® v3.8.4, Copyright ©2000-2009, Jelsoft Enterprises Ltd.