3

I need multiplication of time in PHP

$maritime ='01:10:00';       

I need increment this $maritime in to 5
I want to get answer like this

01:10:00*5 =  05:50:00
pavel
  • 26,538
  • 10
  • 45
  • 61
Biju s
  • 420
  • 1
  • 7
  • 16

3 Answers3

10

Here is what you should do

Step 1 : Convert your hours into seconds

$seconds = strtotime("1970-01-01 $maritime UTC");

Step 2 : Multiply it directly

$multiply = $seconds * 5;

Step 3 : Convert the seconds back to hours, And you're done !

echo gmdate("d H:i:s",$multiply);

So Your final code shall be

<?php
$maritime ='01:10:00';
$seconds = strtotime("1970-01-01 $maritime UTC");
$multiply = $seconds * 5;  #Here you can multiply with your dynamic value
echo gmdate("d H:i:s",$multiply);

Here is the Link of Eval which shows the Output

Update :

If you work with more than one day

i.e., time * 25 times, then it will have more than one day

Then my output will be 02 05:10:00

But if you want it in hours strictly you should use the DateTime

<?php
$maritime ='01:10:00';
$seconds = strtotime("1970-01-01 $maritime UTC");
$multiply = $seconds * 25;  #Here you can multiply with your dynamic value
$seconds = $multiply;
$zero    = new DateTime("@0");
$offset  = new DateTime("@$seconds");
$diff    = $zero->diff($offset);
echo sprintf("%02d:%02d:%02d", $diff->days * 24 + $diff->h, $diff->i, $diff->s);
?>

Here is the Eval Link

Sulthan Allaudeen
  • 11,330
  • 12
  • 48
  • 63
4

Just convert the time to base unit (seconds in this case), then multiply it and convert it back.

Here is a quick example of how to do it, note that there is no error checking in toSeconds and you'll probably want to handle 00 in fromSeconds.

function toSeconds($time){
  $arr = explode(":", $time);
  return $arr[0]*3600 + $arr[1]*60 + $arr[2];
}

function fromSeconds($seconds){
  $hours = floor($seconds/3600);
  $seconds -= $hours*3600;
  $minutes = floor($seconds/60);
  $seconds -= $minutes*60;
  return "$hours:$minutes:$seconds";
}
hynner
  • 1,352
  • 1
  • 11
  • 20
0

Its simple. Try this

$your_time = "01:10:00";
date_default_timezone_set ("UTC");
$secs = strtotime($your_time ) - strtotime("00:00:00");
echo date("H:i:s",$secs * 5);
Vladyslav Panchenko
  • 1,517
  • 1
  • 19
  • 23