2016-11-23 57 views
0

我試圖讓使用PHP中,我有兩個按鈕像時鐘和時鐘輸出時間跟蹤系統,以結束時間。我正在存儲時鐘並在會話變量中計時。現在我的要求是計算時間和計時時間之間的差異。如果您有關於計算的差別清晰的概念時代之間,我如何計算開始使用cookie在PHP

<?php 
if(isset($_POST['start'])) 
{ 
    date_default_timezone_set('Asia/Calcutta'); 
    $time_start=date("Y-m-d h:i:s A"); 
    setcookie('start',$time_start,time()+(36400)*3,'/'); 
    echo "time start now ".$time_start."<br>"; 
} 
if(isset($_POST['end'])) 
{ 
    date_default_timezone_set('Asia/Calcutta'); 
    $time_end=date("Y-m-d h:i:s A"); 
    setcookie('end',$time_end,time()+(36400)*3,'/'); 
    echo "time was ended".$time_end."<br>"; 
?> 
<html> 
    <body> 
    <form method="POST"> 
     <input type="submit" name="start" value="Start"> 
     <br><br> 
     <input type="submit" name="end" value="End"> 
    </form> 
    </body> 
</html> 

回答

1

分享思想的DateTime類有多種方法,可以使與日期很簡單的工作。也許下面的內容將會告訴你如何實現你的目標。

$format='Y-m-d H:i:s'; 
$timezone=new DateTimeZone('Asia/Calcutta'); 

$clockin = new DateTime(date($format, strtotime($_COOKIE['start'])),$timezone); 
$clockout= new DateTime(date($format, strtotime($_COOKIE['end'])), $timezone); 

$diff=$clockout->diff($clockin); 

echo $diff->format('%h hours %i minutes %s seconds'); 

Further reading can be found here

全面測試我很快就寫了這一點 - 它似乎工作就好了!

<?php 
    $cs='shift_start'; 
    $cf='shift_end'; 

    date_default_timezone_set('Europe/London'); 

    if(isset($_POST['start'])){ 
     setcookie($cs, date("Y-m-d h:i:s A"), time()+(36400)*3,'/'); 
    } 
    if(isset($_POST['end'])){ 
     setcookie($cf, date("Y-m-d h:i:s A"), time()+(36400)*3,'/'); 
    } 
?> 
<!doctype html> 
<html> 
    <head> 
     <title>Set cookies and get time difference</title> 
    </head> 
    <body> 
    <form method="post"> 
     <input type="submit" name="start" value="Clock-In"> 
     <input type="submit" name="end" value="Clock-Out"> 
     <br /><br /> 
     <input type='submit' name='show' value='Show duration' /> 
    </form> 
    <?php 
     if(isset($_POST['show'])){ 

       $format='Y-m-d H:i:s'; 
       $timezone=new DateTimeZone('Europe/London'); 

       $clockin = new DateTime(date($format, strtotime($_COOKIE[ $cs ])),$timezone); 
       $clockout= new DateTime(date($format, strtotime($_COOKIE[ $cf ])), $timezone); 

       $diff=$clockout->diff($clockin); 

       echo $diff->format('%h hours %i minutes %s seconds'); 
     } 
    ?> 
    </body> 
</html> 
+0

,但它不工作! – manikandan

+0

我只具有兩個靜態創建的cookie值(分開設置約4分鐘)進行測試,並將其正確顯示'0小時4分49個seconds'作爲差。 – RamRaider