Home > Back-end >  How to convert h:m:s to float and float to h:m:s php
How to convert h:m:s to float and float to h:m:s php

Time:10-10

I want to convert time value with second to float and than do some calculation on it and convert it again to time value using php

I have used the function describe below but it has only hour and minute calculation it display wrong amount if second value is there.

i found this function from time conversion to float

I have used function for convert time to float is

function hours_tofloat($val){
    if (empty($val)) {
        return 0;
    }
    $parts = explode(':', $val);
    return $parts[0]   floor(($parts[1]/60)*100) / 100;
}

hours_tofloat("00:02:37"); if i use above function for 00:02:37 time value it gives me wrong float no 0.03 because above function dose not have option for second. so help me and guide how to calculate it

CodePudding user response:

Modify your code as follows. It will return the time in seconds.

$val = '00:02:37';
function hours_tofloat($val){
    if (empty($val)) {
        return 0;
    }
    $parts = explode(':', $val);
    return (int) (($parts[0] * 60 *60)   $parts[1]*60   $parts[2]);
}

echo hours_tofloat($val);

Output: 00:02:37 = 157

It returns

157

CodePudding user response:

Why don't you use EPOCH time routines? Epoch time is an integer representing seconds based on 1 Jan 1970. You don't need the date part so you can have the following approach:

<?php
  $time = '00:02:37';
  $date = new DateTime("1970-01-01T$time 00:00");
  echo 'Seconds = '.$date->format('U');
?>

Output

Seconds = 157

CodePudding user response:

$val = "00:02:37";
/* function converts time value to float */
function time_to_float($val){
 $parts = explode(':', $val);
 $hour_val = 0;
 $hour_val = $parts[0];
 $min_val    = $parts[1]; 
 $second_val = $parts[2]; 
 return ($hour_val  (($min_val* 1/60)) ($second_val * 1/3600));
}
$value = time_to_float($val);// 0.043611111111111

/* function to convert float to time */
$res = float_to_time($value);//00:02:37

 function float_to_time($value){
    $value1 = explode('.',$value);
    $hours = $value1[0];
    $min_in_float = ($value - $hours) * 60/1;
    $min_val = explode('.',$min_in_float);
    $min_val = $min_val[0];
    $min_in_float = $min_in_float - $min_val;
    $second_val = $min_in_float * 60/1;
    $second_val = round($second_val);
    if($hours < 10){
        $hours = "0".$hours;
    }
    if($min_val < 10){
        $min_val = "0".$min_val;
    }
    if($second_val < 10){
        $second_val = "0".$second_val;
    }
    
    return $hours.":".$min_val.":".$second_val;
 }

I got reference about the calculation from

https://www.calculatorsoup.com/calculators/time/time-to-decimal-calculator.php https://www.calculatorsoup.com/calculators/time/decimal-to-time-calculator.php

  • Related