繁体   English   中英

使用PHP从MySQL打印两个日期之间的业务日期的Ymd列表

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

我有这个MySQL表:

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

假设我们有

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

我想使用PHP echo该范围(星期一至星期五)之间的所有工作日。

从以上范围我想打印:

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

我应该如何以及在哪里开始实现这一目标?

// 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);

看到它正常工作

这将打印日期范围:

$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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM