1. 时区
默认为0区时
设置为中国时间:
date_default_timezone_set('PRC');
2. 获取时间
$t = date('Y-m-d H:i:s');
string date ( string $format [, int $timestamp ] )
参数 | 描述 |
format | 必需。规定时间戳的格式。 |
timestamp | 可选。规定时间戳。默认是当前的日期和时间。 |
参数细节参考:https://www.runoob.com/php/php-date.html
3. 时间戳与时间字符串转换
$unixtime = strtotime(date("Y-m-d H:i"))
$t = date("Y-m-d H:i",$unixtime)
4. 求时间差
$t1 = date_diff(date_create($t0), date_create($time));
$t = $t1->format('%h:%i:%s');
date_create():将时间字符串转为DateTime类型
date_diff():求DateTime类型的差的绝对值
最后通过format将DateTime转换回时间字符串
5. 求时间和
$acc = strtotime($time) + strtotime($res);
$acct = date('H:i:s',$acc);
strtotime():将时间字符串转为时间戳
6. 最后是之前写的两个辅助函数代码
// 施工中
public function diff_time($id,$date,$time){
//取出最新上班时间,与现在时间得出上班时长
$sql = "SELECT max(regtime) FROM reg WHERE id = '$id' AND regdate = '$date' AND type = 1";
$res = $this->connect($sql);
$t0 = mysqli_fetch_assoc($res)['max(regtime)'];
if(!$t0){
return null;
}
else{
$t1 = date_diff(date_create($t0), date_create($time));
$t = $t1->format('%h:%i:%s');
$a=$this->ana($id,$date,$t);
return $t;
}
}
public function ana ($id,$date,$time){
//找当日记录,有则加无则写
$sql = "SELECT time FROM ana WHERE id =\
'$id' AND date = '$date'";
$res = $this->connect($sql);
$res = mysqli_fetch_assoc($res);
if(!$res){
$sql = "insert into ana values ('$id','$date','$time')";
$r = $this->connect($sql);
}
else{
$acc = strtotime($time) + strtotime($res);
$acct = date('H:i:s',$acc);
$sql = "update ana set time = '$time' WHERE id = '$id' AND date = '$date' ";
$r = $this->connect($sql);
}
if(!$r){
return false;
}
return $r;
}