zoukankan      html  css  js  c++  java
  • 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

    推荐阅读PHP 计算日期间隔天数

  • 相关阅读:
    HDU 5546 深搜吧 主要是提取的时候容易重复
    HDU 5543 新型01背包 两端放一半就可以有其价值
    HDU 2586 查找两点之间的距离
    HDU 5652 二分加搜索 http://acm.split.hdu.edu.cn/showproblem.php?pid=5652
    美句
    最短路径问题
    1766 装果子
    Watchcow
    codevs 4768 跳石头
    noi 7219:复杂的整数划分问题
  • 原文地址:https://www.cnblogs.com/ddddemo/p/5624123.html
Copyright © 2011-2022 走看看