php 计算两个日期的间隔天数

使用php内部自带函数实现

1、使用DateTime::diff 实现计算  

参考阅读>>PHP DateTime::diff()

上代码:

 

<?php 
$start = "2016-05-25";
$end = "2016-05-23";

$datetime_start = new DateTime($start);
$datetime_end = new DateTime($end);
var_dump($datetime_start->diff($datetime_end));
复制代码
*结果*

object(DateInterval)[3]
  public 'y' => int 0
  public 'm' => int 0
  public 'd' => int 2
  public 'h' => int 0
  public 'i' => int 0
  public 's' => int 0
  public 'weekday' => int 0
  public 'weekday_behavior' => int 0
  public 'first_last_day_of' => int 0
  public 'invert' => int 1
  public 'days' => int 2
  public 'special_type' => int 0
  public 'special_amount' => int 0
  public 'have_weekday_relative' => int 0
  public 'have_special_relative' => int 0
复制代码

由结果我们知道,想要得出时间差,可以用下面方法实现

$start = "2016-05-25";
$end = "2016-05-23";

$datetime_start = new DateTime($start);
$datetime_end = new DateTime($end);
$days = $datetime_start->diff($datetime_end)->days;
echo "时间差是:$days";
*最终结果为*

时间差是:2

2.date_create()、date_diff()实现

$start = "2016-05-25";
$end = "2016-05-23";

$datetime_start = date_create($start);
$datetime_end = date_create($end);
$days = date_diff($datetime_start, $datetime_end);
var_dump($days);
复制代码
*打印结果*

object(DateInterval)[3]
  public 'y' => int 0
  public 'm' => int 0
  public 'd' => int 2
  public 'h' => int 0
  public 'i' => int 0
  public 's' => int 0
  public 'weekday' => int 0
  public 'weekday_behavior' => int 0
  public 'first_last_day_of' => int 0
  public 'invert' => int 1
  public 'days' => int 2
  public 'special_type' => int 0
  public 'special_amount' => int 0
  public 'have_weekday_relative' => int 0
  public 'have_special_relative' => int 0
复制代码

具体实现:

$start = "2016-05-25";
$end = "2016-05-23";

$datetime_start = date_create($start);
$datetime_end = date_create($end);
$days = date_diff($datetime_start, $datetime_end)->days;
echo "时间间隔是:$days";
*结果*

时间间隔是:2

 

posted @   mingruqi  阅读(618)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
历史上的今天:
2020-02-09 【干货】Chrome插件(扩展)开发全攻略 写在前面
2017-02-09 如何在VirtualBox虚拟机软件上安装Win7虚拟系统
点击右上角即可分享
微信分享提示