在 php 文件中显示两个给定日期之间的所有日期


Display all dates between two given dates in php file

输入:两个日期(eg, oct 1, 2013 to oct 10, 2013)

输出:从开始日期到结束日期的每个日期各一行。

我的代码是这样的:

SELECT LoginDatetime,
       LogoutDatetime
FROM attendance
WHERE LoginDatetime BETWEEN $FromDate AND $ToDate
  AND userid = $_SESSION['loginid']

输出:

Oct 1 2013 9 am & Oct 1 2013 6 pm
Oct 10 2013 9 am & Oct 10 2013 6 pm

意思是,这只给了我这个人在场的日子,但我也想显示他缺席的所有日期

    2013年10月1日
  1. 上午9时至2013年10月1日下午6
  2. 缺席。
  3. 缺席
  4. 2013年10月10日 上午9点 & 2013年10月10日 下午
  5. 6点

有人可以提出解决方案吗?

你需要这样的东西:

$date0 = 'DateTime::createFromFormat('M j, Y', 'Oct 1, 2013');
$date1 = 'DateTime::createFromFormat('M j, Y', 'Oct 10, 2013');
$day   = new 'DateInterval('P1D');
while ($date0 <= $date1) {
    echo $date0->format('M j, Y'), PHP_EOL;
    $date0->add($day);
}

输出:

Oct 1, 2013
Oct 2, 2013
Oct 3, 2013
Oct 4, 2013
Oct 5, 2013
Oct 6, 2013
Oct 7, 2013
Oct 8, 2013
Oct 9, 2013
Oct 10, 2013

您可以添加进一步的检查,以启动while循环以获得所需的行为:

// These could come from the database
$dates    = ['Oct 4, 2013', 'Oct 7, 2013', 'Oct 8, 2013'];
$fromDate = 'Oct 1, 2013';
$toDate   = 'Oct 10, 2013';
// Solution
// Remove comments below in order to always show the start and end dates
//$dates[] = $fromDate;
//$dates[] = $toDate;
$date0 = 'DateTime::createFromFormat('M j, Y', $fromDate);
$date1 = 'DateTime::createFromFormat('M j, Y', $toDate);
$day   = new 'DateInterval('P1D');
while ($date0 <= $date1) {
    $string = $date0->format('M j, Y');
    echo (in_array($string, $dates) ? $string : 'Absent'), PHP_EOL;
    $date0->add($day);
}

输出:

Absent
Absent
Absent
Oct 4, 2013
Absent
Absent
Oct 7, 2013
Oct 8, 2013
Absent
Absent

编辑PHP <5.3

基本示例:

$date0 = new DateTime('Oct 1, 2013');
$date1 = new DateTime('Oct 10, 2013');
while ($date0 <= $date1) {
    echo $date0->format('M j, Y'), PHP_EOL;
    $date0->modify('+1 day');
}

高级示例:

// These could come from the database
$dates    = ['Oct 4, 2013', 'Oct 7, 2013', 'Oct 8, 2013'];
$fromDate = 'Oct 1, 2013';
$toDate   = 'Oct 10, 2013';
// Solution
// Remove comments below in order to always show the start and end dates
//$dates[] = $fromDate;
//$dates[] = $toDate;
$date0 = new DateTime($fromDate);
$date1 = new DateTime($toDate);
while ($date0 <= $date1) {
    $string = $date0->format('M j, Y');
    echo (in_array($string, $dates) ? $string : 'Absent'), PHP_EOL;
    $date0->modify('+1 day');
}