3

如何在 PHP 中获取两个日期之间的天数?

输入:

开始日期:01-01-2013
结束日期:05-01-2013

输出:

周二
周三
周四
周五
周六

试过的代码

$from_date ='01-01-2013';
$to_date ='05-01-2013';

$number_of_days = count_days(strtotime($from_date),strtotime($to_date));

for($i = 1; $i<=$number_of_days; $i++)
{
    $day = Date('l',mktime(0,0,0,date('m'),date('d')+$i,date('y')));
    echo "<br>".$day;       
}


function count_days( $a, $b )
{       
    $gd_a = getdate( $a );
    $gd_b = getdate( $b );
    
    $a_new = mktime( 12, 0, 0, $gd_a['mon'], $gd_a['mday'], $gd_a['year'] );
    $b_new = mktime( 12, 0, 0, $gd_b['mon'], $gd_b['mday'], $gd_b['year'] );
    
    return round( abs( $a_new - $b_new ) / 86400 );
}

我看到帖子在两个日期 PHP 之间查找特定日期的日期

但我没有得到我的结果
请帮助我

4

3 回答 3

4

使用DateTime类,它会简单得多:

$from_date ='01-01-2013';
$to_date ='05-01-2013';

$from_date = new DateTime($from_date);
$to_date = new DateTime($to_date);

for ($date = $from_date; $date <= $to_date; $date->modify('+1 day')) {
  echo $date->format('l') . "\n";
}
于 2013-01-31T06:33:44.180 回答
3
$from_date ='01-01-2013';
$to_date ='05-01-2013';
$start = strtotime($from_date);
$end = strtotime($to_date);
$day = (24*60*60);
for($i=$start; $i<= $end; $i+=86400)
    echo date('l', $i);
于 2013-01-31T06:36:42.590 回答
1
<?php
    function printDays($from, $to) {
        $from_date=strtotime($from);
        $to_date=strtotime($to);
        $current=$from_date;
        while($current<=$to_date) {
            $days[]=date('l', $current);
            $current=$current+86400;
        }

        foreach($days as $key=> $day) {
            echo $day."\n";
        }
    }
    $from_date ='01-01-2013';
    $to_date ='05-01-2013';
    printDays($from_date, $to_date);
?>

date循环遍历给定日期(包括)之间的每一天,然后使用函数将相应的日期添加到数组中。打印出数组和tada!你完成了!

于 2013-01-31T06:41:21.683 回答