2015-11-03 116 views
0

到目前爲止,我嘗試讓兩個日期之間的剩餘,所以我可以用一個進度條時間的百分比..計算時間從百分之兩個日期剩餘

我有下面的代碼我傳遞的兩個日期並做了總和,但我得到一個錯誤。我不確定如果這個錯誤是由於日期格式,如果我可以改變它。

<? 
$start = '2015-11-03 14:05:15'; 
$end = '2015-11-03 18:05:15'; 

$current = '2015-11-03 16:12:15'; 

$completed = (($current - $start)/($end - $start)) * 100; 

?> 

<? print $completed; ?> 

我收到以下錯誤。 警告:除零除

+0

你不能減去那樣的字符串。你應該使用例如時間戳,見http://php.net/manual/en/function.strtotime.php – jeroen

回答

0

你正在使用字符串(基本上,純文本)...所以你不能計算任何東西。 (自1970年開始毫秒),您應該使用該時間戳

http://php.net/manual/fr/function.strtotime.php

$start = strtotime('2015-11-03 14:05:15'); 
$end = strtotime('2015-11-03 18:05:15'); 
$current = strtotime('2015-11-03 16:12:15'); 
+0

輝煌,非常感謝。 –

+0

不客氣!祝你好運 ! –

0

這些都是字符串。你不能減去字符串,並期望事情發揮作用。發生的事情是這樣的:

$start = '2015-11-03 14:05:15'; 
$end = '2015-11-03 18:05:15'; 

既然你做-,PHP這些字符串轉換爲整數:

$new_start = (int)$start; // 2015 
$new_end = (int)$end; // 2015 

$new_end - $new_start -> 0 

需要strtotime()這些值回Unix時間戳,然後你CAN減去這些值,並以秒爲單位獲得差異。

+0

輝煌,非常感謝。 –

2

strtotime將採用日期字符串並將其轉換爲unix標準時間爲秒。

<? 
$start = strtotime('2015-11-03 14:05:15'); 
$end = strtotime('2015-11-03 18:05:15'); 

$current = strtotime('2015-11-03 16:12:15'); 

$completed = (($current - $start)/($end - $start)) * 100; 

?> 

<? print $completed; ?> 
+0

輝煌,非常感謝。 –

0

我建議在strtotime上使用DateTime對象。 DateTime允許您指定創建時間戳的格式,而不是依靠strtotime來神奇地找出它。這使得它更可靠。

例如:

<?php 
$start = DateTime::createFromFormat('Y-m-d H:i:s', '2015-11-03 14:05:15'); 
$end = DateTime::createFromFormat('Y-m-d H:i:s', '2015-11-03 18:05:15'); 
$current = DateTime::createFromFormat('Y-m-d H:i:s', '2015-11-03 16:12:15'); 
$completed = (($current->getTimestamp() - $start->getTimestamp())/($end->getTimestamp() - $start->getTimestamp())) * 100; 
echo $completed; 
?> 

注:datetime對象在PHP 5.3中引入。任何舊版本都不會有DateTime。 (老實說,應該更新原因很多)

+0

嘿,謝謝你。代碼給出了第2行的錯誤。致命錯誤:調用未定義的方法DateTime :: createFromFormat() –

+0

@LiamArmour DateTime :: createFromFormat()在PHP 5.3中引入。最有可能的是你的PHP版本較舊。所以 - 安裝PHP> = 5.3會導致這個工作,否則你堅持strtotime():) –

+0

輝煌,非常感謝。 –

相關問題