Skip to content

Instantly share code, notes, and snippets.

@hedcler
Created July 18, 2014 23:34
Show Gist options
  • Save hedcler/e8284f6ffa819eb7f48a to your computer and use it in GitHub Desktop.
Save hedcler/e8284f6ffa819eb7f48a to your computer and use it in GitHub Desktop.
Funções para calcular intervalo de tempo
<?php
function truncate($value) {
$parts = explode('.',$value);
return $parts{0};
}
function sum_the_time($time1, $time2) {
$seconds = 0;
$times = array($time1, $time2);
foreach($times as $time){
$seconds += timetosec($time);
}
return sectotime($seconds);
}
function timetosec($time){
$_seconds = 0;
list($h,$i,$s) = explode(':', $time);
if ( substr($time, 0, 1) == '-' ) {
$i = '-'.$i;
$s = '-'.$s;
}
$_seconds += ($h*60*60);
$_seconds += ($i*60);
$_seconds += ($s);
return $_seconds;
}
function sectotime($seconds, $with_seconts = TRUE){
// Transforma tudo em Hora minuto e segundo
$hours = truncate($seconds / (60*60));
$minutes = truncate(($seconds / 60) % 60);
$seconds = truncate($seconds % 60);
// Deixa munutos e segundos positivos
$minutes = $minutes < 0 ? -$minutes : $minutes;
$seconds = $seconds < 0 ? -$seconds : $seconds;
// Descarta ponto flutuante
$hours = truncate($hours);
$minutes = truncate($minutes);
$seconds = truncate($seconds);
// Completa com Zeros
$hours = str_pad($hours, 2, '0', STR_PAD_LEFT);
$minutes = str_pad($minutes, 2, '0', STR_PAD_LEFT);
$seconds = str_pad($seconds, 2, '0', STR_PAD_LEFT);
if ( substr($hours, 0, 1) == '-' ) {
$_h = -$hours;
$_h = str_pad($_h, 2, '0', STR_PAD_LEFT);
$hours = '-'.$_h;
}
if ( !$with_seconts ) {
$seconds = '00';
}
// Retorna formatado
return "$hours:$minutes:$seconds";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment