2013-10-16 79 views
0

输入:两个日期(eg, oct 1, 2013 to oct 10, 2013)显示在php文件给定的两个日期之间的所有日期

输出:一行通过开始日期到结束日期每个日期。

我的代码是这样的:

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 

手段,这给了我只有天这个人是存在的,但我想显示所有的日期,他是缺席也

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

有人能提出一个解决办法?

+0

我是在假设 '缺席' 纠正日期在您的数据库中没有条目? – Cups

+0

在滚动浏览返回的查询时,是否可以使用php打印缺席日期? – unska

+1

1.你尝试过什么? 2.如果你搜索这个网站或者使用谷歌,你会发现你的解决方案 –

回答

1

你需要这样的事:

$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 

您可以添加更多checkings insithe的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'); 
} 
+0

道歉没有提及,我使用PHP 5.2.6 – user1808995

+0

@ user1808995完成!这应该与PHP <5.3 – Carlos

+0

@ jackflash一起工作。谢谢很多..它将我的代码切割成几乎一半的简单 – user1808995

相关问题