【问题标题】:Count days within a month from date range从日期范围计算一个月内的天数
【发布时间】:2013-10-18 09:36:43
【问题描述】:

我在mysql表中有三个日期范围如下

  • 从 2013-09-29 到 2013-10-02
  • 从 2013 年 10 月 14 日到 2013 年 10 月 16 日
  • 从2013-10-28到2013-11-05

我只想计算 10 月份发生的天数,例如从第一个范围(2013-09-29 到 2013-10-02)我应该得到两天的差异(10 月 1 日和 2 日),它应该忽略 9 月份的天数,最后我想从上述日期范围计算给定月份的总天数。

可以通过直接mysql查询来完成吗?或任何简短的 PHP 逻辑。

这是我的表结构 id,employee_id,leave_start,leave_to

我正在寻找类似的方法

函数 countLeaves($employee_id,$month) {

// 代码

返回 $numberOfLeaves }

【问题讨论】:

  • 告诉我你从数据库中得到的确切值...
  • 尝试使用gregoriantojd并减去
  • 其实我想统计一个员工一个月内的离职数,所以我的方法是这样的 code function countLeaves($employeeId,$month) { //mysql查询+php逻辑返回 $numberOfDays; } code

标签: php mysql date


【解决方案1】:

您需要计算 2013-10-01 月份的第一天和 2013-10-31 月份的最后一天,然后您可以使用如下查询:

SELECT
  DATEDIFF(
    LEAST(d_end, '2013-10-31'),
    GREATEST(d_start, '2013-10-01'))+1 days
FROM
  ranges
WHERE
  d_start<='2013-10-31' AND d_end>='2013-10-01'

请看小提琴here

【讨论】:

    【解决方案2】:

    函数 getAllDates($fromDate, $toDate,$rejectmonth) { if(!$fromDate || !$toDate) {return false;}

        $dateMonthYearArr = array();
        $fromDateTS = strtotime($fromDate);
        $toDateTS = strtotime($toDate);
        for ($currentDateTS = $fromDateTS; $currentDateTS <= $toDateTS; $currentDateTS += (60 * 60 * 24))
        {
    
            if($rejectmonth == date("m",$currentDateTS))
                continue;
            $currentDateStr = date("Y-m-d",$currentDateTS);
            $dateMonthYearArr[] = $currentDateStr;
        }
        return $dateMonthYearArr;
    }
    

    使用此函数将返回日期范围内的数组日期。

    getAllDates('2013-09-10','2013-19-10',10);

    【讨论】:

      【解决方案3】:
      $month = strtotime(date('Y-m-01', time()));
      $daysCount = (int)(time() - $month) / (24 * 3600);
      

      如果您需要从任何日期到任何日期进行检查:

      /**
      * @var $dateFrom string Date to count from, 
      * you can use date('Y-m-01') as start of current month
      * @var $dateTo string End of period date, example: '2013-09-05'
      **/
      function getDaysCount($dateFrom, $dateTo)
      {
          return (int)(strtotime($dateTo) - strtotime($dateFrom)) / (24 * 3600);
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-03-08
        • 2011-02-05
        • 1970-01-01
        • 1970-01-01
        • 2019-04-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多