2016-11-03 3 views
-1

に小数を変換する が、それはすべてのコードで動作し、テストされていない、元の文字列をエクセル などからである。どのように私はPHPでの作業と時間(HH:MM)に小数を変換しようとしていた時間

0.625 = 15:00 
0.53541666666667 = 12:51 
0.40277777777778 = 09:40 
+2

「0.625」は「15:00」とどのように等しくなりますか? –

+1

ああ、私はそれを持って、0.625 * 24 = 15 – manu

+0

あなたは動作しなかったあなたのコードを表示できますか? – simon

答えて

3
$dec = 0.625; 

これは単純です。

function convertTime($dec) 
{ 
    // start by converting to seconds 
    $seconds = ($dec * 3600); 
    // we're given hours, so let's get those the easy way 
    $hours = floor($dec); 
    // since we've "calculated" hours, let's remove them from the seconds variable 
    $seconds -= $hours * 3600; 
    // calculate minutes left 
    $minutes = floor($seconds/60); 
    // remove those from seconds as well 
    $seconds -= $minutes * 60; 
    // return the time formatted HH:MM:SS 
    return lz($hours).":".lz($minutes).":".lz($seconds); 
} 

// lz = leading zero 
function lz($num) 
{ 
    return (strlen($num) < 2) ? "0{$num}" : $num; 
} 

echo convertTime($hours); 

出典:How to convert a decimal into time, eg. HH:MM:SS

出力時間を小数から変換するには、このhours:mins使用に小数点から変換するために、今24

$hours = $dec * 24; 

との乗算を行います:http://ideone.com/Q7lkwX

4

通常、手動で作業するのではなく、任意の日付演算にDateTimeクラスを使用することをお勧めします。あなたの質問からは、それが望まれるかどうかは明らかではありませんが、夏時間の節約などについて考慮されます。

<?php 
/** 
* @param float $x Decimal number of hours 
* @return string HH:mm 
*/ 
function dec_hours($x) { 
    $sec = intval($x * (24 * 60 * 60)); 
    $date = new DateTime("today +$sec seconds"); 
    return $date->format('H:i'); 
} 

echo dec_hours(0.625);   // 15:00 
echo dec_hours(0.53541666666667); // 12:51 
echo dec_hours(0.40277777777778); // 09:40 
+0

これは私にとって完璧です! – a2rgzz

関連する問題