Print Y-m-d list of business dates between two dates from MySQL using PHP

∥☆過路亽.° 提交于 2019-12-04 05:49:12

问题


I have this MySQL table:

desc studentabsence;
+---------------------------+-------------+
| Field                     | Type        |
+---------------------------+-------------+
| student_id                | INT(11)     |
| student_absence_startdate | date        |
| student_absence_enddate   | date        |
+---------------------------+-------------+

Let's say that we have

student_absence_startdate = 2012-08-01
student_absence_enddate = 2012-08-08

Using PHP, I would like to echo all business days between that range (Mon-Fri).

From the above range I would like to print:

2012-08-01
2012-08-02
2012-08-03
2012-08-06
2012-08-07
2012-08-08

How and where should I start to achieve this?


回答1:


// Date strings from DB
$startDate = '2012-08-01';
$endDate = '2012-08-08';

// Convert to UNIX timestamps
$currentTime = strtotime($startDate);
$endTime = strtotime($endDate);

// Loop until we reach the last day
$result = array();
while ($currentTime <= $endTime) {
  if (date('N', $currentTime) < 6) {
    $result[] = date('Y-m-d', $currentTime);
  }
  $currentTime = strtotime('+1 day', $currentTime);
}

// Show the result
// You could loop the array to pretty-print it, or do it within the above loop
print_r($result);

See it working




回答2:


This will print the range of dates:

$startDate = '2012-08-01';
$endDate = '2012-08-08';

$date = new DateTime($startDate);
while ($date->format('Y-m-d') != $endDate) {

    if ($date->format('N') > 5) {
        $date->modify('+1 day');
        continue;
    }

    echo $date->format('Y-m-d') . PHP_EOL;
    $date->modify('+1 day');
}
echo $endDate;


来源:https://stackoverflow.com/questions/11904033/print-y-m-d-list-of-business-dates-between-two-dates-from-mysql-using-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!