1

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

  • 从 2013 年 9 月 29 日到 2013 年 10 月 2 日
  • 从 2013 年 10 月 14 日到 2013 年 10 月 16 日
  • 从 2013 年 10 月 28 日到 2013 年 11 月 5 日

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

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

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

我正在寻找一种方法,例如

函数 countLeaves($employee_id,$month) {

// 代码

返回 $numberOfLeaves }

4

3 回答 3

2

您需要计算 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'

在此处查看小提琴。

于 2013-10-18T09:52:35.973 回答
0

函数 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);

于 2013-10-18T09:54:08.603 回答
0
$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);
}
于 2013-10-18T09:43:45.600 回答