簡體   English   中英

PHP的時間和時間

[英]PHP round time and hours

我需要四舍五入。 我想知道如何將時間舍入到下一個小時並將其用作PHP中的int。

例如:

24:00:02 -> 25  
33:15:05 -> 34  
48:40:30 -> 49

有任何想法嗎?

問候克勞迪奧

您想要類似DateTime :: setTime的東西。 使用日期功能提取小時/分鍾/秒,確定是否需要增加小時,然后將小時設置為適當的值,並將分鍾和秒清零。

嗯。 在再次閱讀您的問題時,像這樣:

$sec = date('s', $timevalue);
$min = date('i', $timevalue);
$hour = date('G', $timevalue);

if (($sec > 0) or ($min > 0)) { $hour++; } // if at x:00:01 or better, "round up" the hour

我假設您使用的格式為HOURS:MINUTES:SECONDS,表示持續時間而不是一天中的某個時間,並且我假設您已經將此值作為字符串使用。 在這種情況下,您的解決方案是自釀功能,因為這是一個非常具體的情況。 像這樣:

function roundDurationUp($duration_string='') {
     $parts = explode(':', $duration_string);
     // only deal with valid duration strings
     if (count($parts) != 3)
       return 0;

     // round the seconds up to minutes
     if ($parts[2] > 30)
       $parts[1]++;

     // round the minutes up to hours
     if ($parts[1] > 30)
       $parts[0]++;

     return $parts[0];
    }

print roundDurationUp('24:00:02'); // prints 25
print roundDurationUp('33:15:05'); // prints 34
print roundDurationUp('48:40:30'); // prints 49

試試看: http : //codepad.org/nU9tLJGQ

function ReformatHourTime($time_str){
                $min_secs = substr($time_str,3);
                $direction = round($min_secs/60);

                if($dir == 1){
                    return $time_str+1;
                }else{
                    return floor($time_str);
                }
         }

如果您將時間字符串當作一個數字來處理,PHP會將其當作一個數字對待,並除去除前兩位以外的所有內容。

print '48:40:30' + 1; # 49
print '30:00:00' + 1; # 31

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM