PHP Seconds to MM:SS Function - php

Currently I use the following javascript function to conver seconds to minutes and seconds.
function fmtMSS(s){return(s-(s%=60))/60+(9<s?':':':0')+s}
If I pass it 235 it returns 3:55
I've tried to convert it to php, but passing 235 to it I get 55
What have I done wrong ?
function fmtMSS($s){
return($s-($s%=60))/60+(9<$s?':':':0')+$s;
};
echo fmtMSS(235);
Thanks.

You have wrong logic part in your PHP version. Take a look at this:
function fmtMSS($s){
return(($s-($s%60))/60).(9<$s?':':':0').$s%60;
};
echo fmtMSS(235);
Sandbox: http://sandbox.onlinephpfunctions.com/code/163b767d435cf9db9058d03e95b873fb07e3fcbd

There is no reason to do it in a one-liner unless its the easiest and most readable way. Don't sacrifice readable code for shorter code.
The below function is the simplest and easiest way to convert seconds into a minute:seconds format. The reason for not using date("H:i", $s) (which would yield the same result) is that it will not scale well, and return incorrect results if $s ever gets high.
Divide by 60, floor it - that will get you the minutes. Multiply it by 60 and subtract it from $s, and you have your seconds.
function fmtMSS($s){
$minutes = floor($s/60);
$seconds = $s-$minutes*60;
return "$minutes:$seconds";
};
echo fmtMSS(235); // 3:55
Live demo
The reason your original code doesn't work, is because you're using + to join strings (as you would in JavaScript). However, in PHP, one uses . to contact two strings. The logic also seems to be a bit incorrect.

<?php
function fmtMSS($s){
$min = floor($s/60);
$sec = $s%60;
return $min.':'.$sec;
};
echo fmtMSS(235);
?>
Use this code- i have just edited your function.
for short:- echo gmdate("i:s", 235);

Related

How to get log() of a very big number (PHP)?

I've looked at php-big numbers, BC Math, and GMP for dealing with very big numbers in php. But none seem to have a function equivilent to php's log(). For example I want to do this:
$result = log($bigNumber, 2);
Would anyone know of an alternate way to get the log base 2 of a arbitray precision point number in php? Maybe Ive missed a function, or library, or formula.
edit: php-bignumbers seems to have a log base 10 function only log10()
In general if you want to implement your high precision log own calculation, I'd suggest 1st use the basic features of logarithm:
log_a(x) = log_b(x) / log_b(a) |=> thus you can recalulate logarith to any base
log(x*y) = log(x) + log(y)
log(a**n) = n*log(a)
where log_a(x) - meaning logarithm to the base a of x; log means natural logarithm
So log(1000000000000000000000.123) = 21*log(1.000000000000000000000123)
and for high precision of log(1+x)
use algorithm referenced at
http://en.wikipedia.org/wiki/Natural_logarithm#High_precision
One solution combining the suggestions so far would be to use this formula:
log2($num) = log10($num) / log10(2)
in conjunction with php-big numbers since it has a pre-made log10 function.
eg, after installing the php-big numbers library, use:
$log2 = log10($bigNum) / log10(2);
Personally I've decided to use different math/logic so as to not need the log function, and just using bcmath for the big numbers.
One of the great things about base 2 is that counting and shifting become part of the tool set.
So one way to get a 'log2' of a number is to convert it to a binary string and count the bits.
You can accomplish this equivalently by dividing by 2 in a loop. But it seems to me that counting would be more efficient.
gmp_scan0 and gmp_scan1 can be used if you are counting from the right. But you'd have to somehow convert the mixed bits to all ones and zeroes.
But using gmp_strval(num, 2), you can produce a string and do a strpos on it.
if the whole value is being converted, you can do a (strlen - 1) on it.
Obviously this only works when you want an integer log.
I've had a very similar problem just recently.. and so I just scaled the number considerably in order to use the inbuild log to find the fractional part.. (I prefere the log10 for some reason.. don't ask... people are strange, me too)
I hope this is selfexplanatory enough..
it returns a float value (since that's what I needed)
function gmp_log($num, $base=10, $full=true)
{
if($base == 10)
$string = gmp_strval($num);
else
$string = gmp_strval($num,$base);
$intpart = strlen($string)-1;
if(!$full)
return $intpart;
if($base ==10)
{
$string = substr_replace($string, ".", 1, 0);
$number = floatval($string);
$lg = $intpart + log10($number);
return $lg;
}
else
{
$string = gmp_strval($num);
$intpart = strlen($string)-1;
$string = substr_replace($string, ".", 1, 0);
$number = floatval($string);
$lg = $intpart + log10($number);
$lb = $lg / log10($base);
return $lb;
}
}
it's quick, it's dirty... but it works well enough to get the log of some RSA sized integers ;)
usage is straight forward as well
$N = gmp_init("11002930366353704069");
echo gmp_log($N,10)."\n";
echo gmp_log($N,10, false)."\n";
echo gmp_log($N,2)."\n";
echo gmp_log($N,16)."\n";
returns
19.041508364472
19
63.254521604973
15.813630401243

compare times with hundredths in php

I try to compare two swim times in php. They are like HH:MM:SS.XX (XX are hundreths). I get them as string and i want to find out which swimmer is faster. I tryed to convert them using strtotime(). It works with hours, minutes and seconds but it ignores hundreths. Here is my code for better explanation:
$novy = strtotime($input1);
$stary = strtotime($input2);
if($novy < $stary){
//change old(stary) to new(novy)
}
If $input1 is 00:02:14.31 and $input2 is 00:02:14.32 both $novy and $stary are 1392850934.
I read some solution to similar problem in javascript but I can`t use it, this must be server-side.
Thank you for help.
If you use date_create_from_format you can specify the exact date format for php to convert the string representations to:
<?php
$input1 = '00:02:14.31';
$input2 = '00:02:14.32';
$novy = date_create_from_format('H:i:s.u', $input1);
$stary = date_create_from_format('H:i:s.u',$input2);
if ($novy < $stary) {
echo "1 shorter\n";
} else {
echo "2 longer\n";
}
Recommended reading: http://ie2.php.net/datetime.createfromformat
If the format is really HH:MM:SS.XX (ie: with leading 0's), you can just sort them alphabetically:
<?php
$input1 = '00:02:14.31';
$input2 = '00:02:14.32';
if ($input1 < $input2) {
echo "1 faster\n";
} else {
echo "2 faster\n";
}
It prints 1 faster
You could write some conditional logic to test if HH::MM::SS are identical, then simply compare XX, else use the strtotime() function that you are already using
You are working with durations, not dates. PHP's date and time functions aren't really of any help here. You should parse the string yourself to get a fully numeric duration:
$time = '00:02:14.31';
sscanf($time, '%d:%d:%d.%d', $hours, $minutes, $seconds, $centiseconds);
$total = $centiseconds
+ $seconds * 100
+ $minutes * 60 * 100
+ $hours * 60 * 60 * 100;
var_dump($total);
The total is in centiseconds (100th of a second, the scale of your original input). Multiply/divide by other factors to get in others scales, as needed.

Looking to get millisecondes value from: microtime(true) and number_format()

Ok, I know this is not the first question about microtime and number_format but it seem there is no one able to come up with a dummy proof answer. So, as the dummy, here is my question:
How can I output my result from 2 microtime(true) variables in millisecondes. By that I mean 1 being 1 milliseconds and 1000 being 1 secondes.
So if it took less then a millisecondes, i get 1. If it took 1/2 of a second, I get 500.
I currently do this:
number_format((microtime(true)-$timetrace), 4)
And I get this:
1,391,490,671.8339
=)
$timetrace was set before in the code as $timetrace = microtime(true). Thansk for the help and if this was answer before in a one line command, I am truly sorry for asking that again.
This has nothing to do with number_format.
My bet is, you did not put what you intended in your $timetrace variable.
See this example:
<?php
$timetrace = microtime(true);
sleep (1); // wait about 1 second
$elapsed_time = microtime(true) - $timetrace;
echo "$elapsed_time<br>";
echo number_format($elapsed_time, 4) . "<br>";
?>
output:
1.0120580196381
1.0121
Based on kuroi neko suggestion, I did built a little funciton and it work perfectly! Thank you a lot!!
Function ms($overall=0)
{
global $timetrace;
global $starttrace;
if ($overall==1){
$result = microtime(true) - $initialtrace;
}else{
$result = microtime(true) - $timetrace;
}
$result = number_format($result, 4);
$result = $result * 1000;
if ($result < 1)$result = 1;
// Reset timetrace
$timetrace = microtime(true);
return $result." ms<br>";
}
In the code I just have to put:
if (isset($timetrace)) echo "CPU$==# initiation time = ".ms();
That give me the time spent between my last echo. (isset is actually a variable I configure at the beginning to see if I am in 'time debugging mode')
If I pass 1 - echo "CPU$==# initiation time = ".ms(1); - I get the result of the total duration of the script since the top of the page instead of the last echo.
Here is a sample of the output:
CPU$==# INSERT = 12.4 ms
CPU$==# DATE SET FOR GOOGLE QUERY = 530.4 ms
CPU$==# GOOGLE QUERY EXECUTED = 308.8 ms
CPU$==# INSERT 606 ROW = 12290.3 ms
CPU$==# CLOSE LOG WITH SUCCESS = 25.4 ms
Success
And yeah, performance is really terrible. The first 530 ms just to prepare the google query is way too high and 12 seconds to insert 600 rows is insane. Something is badly broken somewhere! =) But at least, now I will be able to benchmark my progression.
Thank you!!!

How to convert a "decimal string" into an integer without the period in PHP

If I have, say, 8.1 saved as a string/plaintext, how can I change that into the integer (that I can do addition with) 81? (I've got to remove the period and change it into an integer. I can't seem to figure it out even though I know it should be simple. Everything I try simply outputs 1.)
You can also try this
$str = '8.1';
$int = filter_var($str, FILTER_SANITIZE_NUMBER_INT);
echo $int; // 81
echo $int+1; // 82
DEMO.
If you're dealing with whole numbers (as you said), you could use the intval function that is built into PHP.
http://php.net/manual/en/function.intval.php
So basically, once you have your string parsed and setup as a whole number you can do something like:
intval("81");
And get back the integer 81.
Example:
$strNum = "81";
$intNum = intval($strNum);
echo $intNum;
// "81"
echo getType($intNum);
// "integer"
Since php does auto-casting, this should work:
<?php
$str="8432.145522";
$val = str_replace('.','', $str);
print $str." : ".$val;
?>
Output:
8432.145522 : 8432145522
Not sure if this will work. But if you always have something.something,(like 1.1 or 4.2), you can multiply by 10 and do intval('string here'). But if you have something.somethingsomething or with more somethings(like 1.42 and 5.234267, etc.), I don't know what to say. Maybe a function to keep multiplying by ten until it's an integer with is_int()?
Sources:
http://php.net/manual/en/function.intval.php
http://php.net/manual/en/function.is-int.php
Convert a string to a double - is this possible?

PHP variable not incremented

I have a small code as part of a huge file as follows:
if(($lastLogTime + $logOffset)>= $text1)
{
echo $text1.'<br>';
$uptime=$uptime + (($text1 - $lastLogTime)/60000);
echo ($text1 - $lastLogTime).'<br>';
fwrite($fd, $uptime.',');
echo $uptime.'<br><br>';
$lastLogTime = ($lastLogTime + 1800000);
echo $lastLogTime.' ME <br>';
}
The weird part is the output for the final $lastLogTime is NOT getting added by the 1800000 OR a variable called $logInterval = 1800000 which was initialized earlier.
The output is
1298083876650 - i.e lastLogtime
1298083877661 - text1
1011 - the difference
0.01685 - uptime
1298085676650 ME - damn ! doesn't get added by 1800000
NEW EDIT :
I solved it ! bad answers guys.. Thanks for the time anyways.
Am i the only one facing weird shhit like this ?
I suspect it has something to do with this:
What's the maximum size for an int in PHP?
Check out the php date function. Though working with dates can be tedious, converting everything to seconds normally isn't the best approach.
http://php.net/manual/en/function.date.php

Categories