PHP multiply time by an integer value?

3

How do I multiply hours in PHP ?

Example:

$time = "0:01:00";
$mult = "5";

echo $time*$mult;

Return was zero, because it did not return 00:05:00 ?

    
asked by anonymous 31.07.2017 / 20:40

2 answers

5
  

The return was zero because it did not return 0:05:00?

The return was zero because you're trying to multiply strings , and the conversion of PHP will interpret only the first digit 0 of your time, making "0:01:00" to 0 , so you're doing 0 * 5 = 0 .

  

How do I multiply hours in php?

If you want, as reported in the comments, to multiply the total value by some multiplier, work with timestamp through the function strtotime and to format the time, use date :

$time = "0:01:00";
$mult = "5";

var_dump(date("H:i:s", strtotime("00:01:00") * $mult));
var_dump(date("H:i:s", strtotime("01:07:37") * $mult));

The result will be:

string(8) "00:05:00"
string(8) "05:38:05"

See working at ideone .

@edit

  

How do I return 1 day and 1:00:00?

If you need this count, you can do this using timestamp from the start day of it:

$time ='01:00:00';
$mult = 5;

$calculated = strtotime("1970-01-01 $time") * $mult;
$date = date("d H:i:s", $calculated);

$datePart = explode(" ", $date);

printf("%s dia(s) %s", $datePart[0]-1, $datePart[1]);

Will result in:

0 dia(s) 05:00:00
1 dia(s) 01:00:00
    
31.07.2017 / 21:35
7

You need to use the DateTime class, where in it there is the modify method so you can modify your date according to your needs.

$time="0:01:00";
$mult="5";
$datetime=DateTime::createFromFormat('H:i:s',$time,new DateTimeZone('America/Sao_Paulo'));
$datetime->modify('+' . $mult . ' minutes');
echo $datetime->format('H:i:s');

EDIT : In this case you can then take the amount of minutes and multiply by the desired value, like this:

$time="00:01:00";
$mult=5;
$datetime=DateTime::createFromFormat('H:i:s',$time,new DateTimeZone('America/Sao_Paulo'));
$minute=$datetime->format('i');
$datetime->modify('+' . ($minute * $mult) . ' minutes');
$datetime->modify('-' . $minute  . ' minutes');
echo $datetime->format('H:i:s');

In addition, I set to use the time on 24 and the TimeZone of São Paulo

    
31.07.2017 / 20:50