Time format with sprintf

Asked

Viewed 39 times

1

I have the following problem, I am working with hours in php.

I have to calculate the time interval, between the start time and the end time, for this I am using the following code.

$entrada = $dados[$z]['hora_inicio'];

if($dados[$z]['hora_fim'] != ""){
    $saida   = $dados[$z]['hora_fim'];
}else{
    $saida = date('H:i');
}

$entrada = explode( ':', $entrada );
$saida   = explode( ':', $saida );
$minutos = ( $saida[0] - $entrada[0] ) * 60 + $saida[1] - $entrada[1];


if( $minutos < 0 ) $minutos += 24 * 60;

print sprintf( '%d:%d', $minutos / 60, $minutos % 60 );?>

And the format returned is 0:0, but I need the following format 00:00, some hint of how I can change the format, so that it stays 00:00?

  • 1

    To correct this would be enough to use: %02d:%02d instead of %d:%d.

  • thank you very much, meta as a response, because it worked perfectly

1 answer

2


Just change the last line to the following:

print sprintf( '%02d:%02d', $minutos / 60, $minutos % 60 );

Browser other questions tagged

You are not signed in. Login or sign up in order to post.