从日期范围开始计算一个月内的天数

时间:2013-10-18 09:36:43

标签: php mysql date

我在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月),它应该忽略九月份的天数,最后我想计算一个月内从上述日期范围开始的总天数。

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

这是我的表格结构 ID,EMPLOYEE_ID,leave_start,leave_to

我正在寻找一种类似

的方法

function countLeaves($ employee_id,$ month) {

//代码

返回$ numberOfLeaves }

3 个答案:

答案 0 :(得分: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'

请参阅小提琴here

答案 1 :(得分: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);
}

答案 2 :(得分:0)

function 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年9月10日', '2013-19-10',10);

相关问题