我在 PHP 中有 2 个日期,如何运行 foreach 循环来完成所有这些日子?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3207749/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 09:00:27  来源:igfitidea点击:

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

phpforeachdate

提问by Shamoon

I'm starting with a date 2010-05-01and ending with 2010-05-10. How can I iterate through all of those dates in PHP?

我以日期开始2010-05-01并以2010-05-10. 如何在 PHP 中遍历所有这些日期?

回答by Gordon

Requires PHP5.3:

需要 PHP5.3:

$begin = new DateTime('2010-05-01');
$end = new DateTime('2010-05-10');

$interval = DateInterval::createFromDateString('1 day');
$period = new DatePeriod($begin, $interval, $end);

foreach ($period as $dt) {
    echo $dt->format("l Y-m-d H:i:s\n");
}

This will output all days in the defined period between $startand $end. If you want to include the 10th, set $endto 11th. You can adjust format to your liking. See the PHP Manual for DatePeriod.

这将输出$start和之间定义的时间段内的所有天数$end。如果要包括第 10 个,请设置$end为第 11 个。您可以根据自己的喜好调整格式。请参阅DatePeriod的 PHP 手册。

回答by Sabri Aziri

This also includes the last date

这也包括最后日期

$begin = new DateTime( "2015-07-03" );
$end   = new DateTime( "2015-07-09" );

for($i = $begin; $i <= $end; $i->modify('+1 day')){
    echo $i->format("Y-m-d");
}

If you dont need the last date just remove =from the condition.

如果您不需要最后日期,只需=从条件中删除。

回答by Harold1983-

Converting to unix timestamps makes doing date math easier in php:

转换为 unix 时间戳使得在 php 中进行日期数学更容易:

$startTime = strtotime( '2010-05-01 12:00' );
$endTime = strtotime( '2010-05-10 12:00' );

// Loop between timestamps, 24 hours at a time
for ( $i = $startTime; $i <= $endTime; $i = $i + 86400 ) {
  $thisDate = date( 'Y-m-d', $i ); // 2010-05-01, 2010-05-02, etc
}

When using PHP with a timezone having DST, make sure to add a time that is not 23:00, 00:00 or 1:00 to protect against days skipping or repeating.

使用带有 DST 的时区的 PHP 时,请确保添加不是 23:00、00:00 或 1:00 的时间,以防止跳过或重复天数。

回答by Alexander Kharchenko

Copy from php.net sample for inclusiverange:

包含范围的php.net 示例复制:

$begin = new DateTime( '2012-08-01' );
$end = new DateTime( '2012-08-31' );
$end = $end->modify( '+1 day' ); 

$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);

foreach($daterange as $date){
    echo $date->format("Ymd") . "<br>";
}

回答by Mark Baker

$startTime = strtotime('2010-05-01'); 
$endTime = strtotime('2010-05-10'); 

// Loop between timestamps, 1 day at a time 
$i = 1;
do {
   $newTime = strtotime('+'.$i++.' days',$startTime); 
   echo $newTime;
} while ($newTime < $endTime);

or

或者

$startTime = strtotime('2010-05-01'); 
$endTime = strtotime('2010-05-10'); 

// Loop between timestamps, 1 day at a time 
do {
   $startTime = strtotime('+1 day',$startTime); 
   echo $startTime;
} while ($startTime < $endTime);

回答by HADI

Here is another simple -

这是另一个简单的 -

/**
 * Date range
 *
 * @param $first
 * @param $last
 * @param string $step
 * @param string $format
 * @return array
 */
function dateRange( $first, $last, $step = '+1 day', $format = 'Y-m-d' ) {
    $dates = [];
    $current = strtotime( $first );
    $last = strtotime( $last );

    while( $current <= $last ) {

        $dates[] = date( $format, $current );
        $current = strtotime( $step, $current );
    }

    return $dates;
}

Example:

例子:

print_r( dateRange( '2010-07-26', '2010-08-05') );

Array (
    [0] => 2010-07-26
    [1] => 2010-07-27
    [2] => 2010-07-28
    [3] => 2010-07-29
    [4] => 2010-07-30
    [5] => 2010-07-31
    [6] => 2010-08-01
    [7] => 2010-08-02
    [8] => 2010-08-03
    [9] => 2010-08-04
    [10] => 2010-08-05
)

回答by user2182143

User this function:-

使用此功能:-

function dateRange($first, $last, $step = '+1 day', $format = 'Y-m-d' ) {
                $dates = array();
                $current = strtotime($first);
                $last = strtotime($last);

                while( $current <= $last ) {    
                    $dates[] = date($format, $current);
                    $current = strtotime($step, $current);
                }
                return $dates;
        }

Usage / function call:-

用法/函数调用:-

Increase by one day:-

增加一天:-

dateRange($start, $end); //increment is set to 1 day.

Increase by Month:-

按月增加:-

dateRange($start, $end, "+1 month");//increase by one month

use third parameter if you like to set date format:-

如果您想设置日期格式,请使用第三个参数:-

   dateRange($start, $end, "+1 month", "Y-m-d H:i:s");//increase by one month and format is mysql datetime

回答by Jean Souza

here's a way:

这是一种方法:

 $date = new Carbon();
 $dtStart = $date->startOfMonth();
 $dtEnd = $dtStart->copy()->endOfMonth();

 $weekendsInMoth = [];
 while ($dtStart->diffInDays($dtEnd)) {

     if($dtStart->isWeekend()) {
            $weekendsInMoth[] = $dtStart->copy();
     }

     $dtStart->addDay();
 }

The result of $weekendsInMoth is array of weekend days!

$weekendsInMoth 的结果是周末天数的数组!

回答by zukayu

$date = new DateTime($_POST['date']);
$endDate = date_add(new DateTime($_POST['date']),date_interval_create_from_date_string("7 days"));

while ($date <= $endDate) {
    print date_format($date,'d-m-Y')." AND END DATE IS : ".date_format($endDate,'d-m-Y')."\n";
    date_add($date,date_interval_create_from_date_string("1 days"));
}

You can iterate like this also, The $_POST['date']can be dent from your app or website Instead of $_POST['date']you can also place your string here "21-12-2019". Both will work.

你也可以像这样迭代,$_POST['date']可以从你的应用程序或网站中提取出来,而不是$_POST['date']你也可以把你的字符串放在这里"21-12-2019"。两者都会起作用。

回答by Victor Nu?ez

If you use Laravel and want to use Carbon the correct solution would be the following:

如果您使用 Laravel 并想使用 Carbon,正确的解决方案如下:

$start_date = Carbon::createFromFormat('Y-m-d', '2020-01-01');
$end_date = Carbon::createFromFormat('Y-m-d', '2020-01-31');

$period = new CarbonPeriod($start_date, '1 day', $end_date);

foreach ($period as $dt) {
 echo $dt->format("l Y-m-d H:i:s\n");
}

Remember to add:

记得补充:

  • use Carbon\Carbon;
  • use Carbon\CarbonPeriod;
  • 使用碳\碳;
  • 使用碳\碳周期;