2014-02-20 59 views
0

我嘗試比較php中的兩次游泳次數。他們就像HH:MM:SS.XXXX是hundreths)。我把它們作爲字符串,我想找出哪個游泳運動員更快。我試着用strtotime()來轉換它們。它適用於小時,分鐘和秒鐘,但它忽略了洪流。這裏是我更好的解釋代碼:與php中的百分比比較次數

$novy = strtotime($input1); 
$stary = strtotime($input2); 
if($novy < $stary){ 
    //change old(stary) to new(novy) 
} 

如果$input100:02:14.31$input200:02:14.3 2都$novy$stary1392850934。 我讀了一些JavaScript解決方案,但我不能使用它,這必須是服務器端。 謝謝你的幫助。

+0

** [MICROTIME](http://www.php.net/manual/de/function.microtime.php)**可能有幫助嗎?像$ novy = strtotime($ input1,microtime()); – Dwza

回答

0

如果格式是真的HH:MM:SS.XX(即:與領先0的),你ç一個只按字母順序排序他們:

<?php 
$input1 = '00:02:14.31'; 
$input2 = '00:02:14.32'; 
if ($input1 < $input2) { 
    echo "1 faster\n"; 
} else { 
    echo "2 faster\n"; 
} 

它打印1 faster

+0

這工作正常,但我不知道它會一直工作。我不知道是否最好的想法是將數字信息作爲字符串進行比較。 –

+0

如果您的所有輸入都具有相同的格式,那麼就沒有問題了。通常在將日期與YYYY-MM-DD格式進行比較時完成。如果你不寫前面的0,你可能會面臨問題。 –

0

你可以寫一些有條件的邏輯來測試,如果HH :: MM :: SS相同,則簡單地比較XX,別人使用你已經使用

1

中的strtotime()函數,如果使用date_create_from_format可以指定確切的日期格式爲PHP的字符串表示轉換爲:

<?php 
$input1 = '00:02:14.31'; 
$input2 = '00:02:14.32'; 
$novy = date_create_from_format('H:i:s.u', $input1); 
$stary = date_create_from_format('H:i:s.u',$input2); 
if ($novy < $stary) { 
    echo "1 shorter\n"; 
} else { 
    echo "2 longer\n"; 
} 

推薦閱讀:http://ie2.php.net/datetime.createfromformat

+0

我不知道爲什麼,但我不僅沒有得到hundreths,但也秒。這裏是'$ input2''object(DateTime)的var_dump [2] public'date'=> string'2014-02-21 00:02:14'(length = 19) public'timezone_type'=> int 3 public'timezone'=> string'UTC'(length = 3)' –

+0

確實如此。沒有提到你不想要秒,而且問題是百分之幾秒被忽略 - 這個解決方案完美地解決了這個問題。 – kguest

0

您與持續時間,沒有日期的工作。 PHP的日期和時間函數在這裏沒有任何幫助。你應該自己解析字符串得到一個完全數字時間:

$time = '00:02:14.31'; 

sscanf($time, '%d:%d:%d.%d', $hours, $minutes, $seconds, $centiseconds); 
$total = $centiseconds 
     + $seconds * 100 
     + $minutes * 60 * 100 
     + $hours * 60 * 60 * 100; 

var_dump($total); 

總在釐秒(1/100秒,你的原始輸入的規模)。根據需要乘以/除以其他因素以獲得其他比例。

+0

這工作正常 –