PHP 时间操作

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;
}
  

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值