我正在尝试使用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>
答案 0 :(得分: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>