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

问题描述 投票:0回答:16

我以约会

2010-05-01
开始,以
2010-05-10
结束。如何在 PHP 中迭代所有这些日期?

php foreach date
16个回答
667
投票
$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");
}

这将输出定义期间

$start
$end
之间的所有日期。如果您想包含第 10 个,请将
$end
设置为第 11 个。您可以根据自己的喜好调整格式。请参阅 PHP 手册了解 DatePeriod。它需要 PHP 5.3。


125
投票

这还包括最后日期

$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");
}

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

=


49
投票

转换为 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
}

在具有 DST 的时区中使用 PHP 时,请确保添加不是 23:00、00:00 或 1:00 的时间,以防止日期跳过或重复。


30
投票

从 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>";
}

24
投票

这是另一个简单的实现 -

/**
 * 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;
}

示例:

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
)

17
投票
$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);

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

5
投票

使用此功能:-

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

使用/函数调用:-

增加一天:-

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

逐月增加:-

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

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

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

4
投票

对于
Carbon
用户

use Carbon\Carbon;

$startDay = Carbon::parse("2021-08-01");
$endDay= Carbon::parse("2021-08-05");
$period = $startDay->range($endDay, 1, 'day');

当我打印数据时

[
     Carbon\Carbon @1627790400 {#4970
       date: 2021-08-01 00:00:00.0 America/Toronto (-04:00),
     },
     Carbon\Carbon @1627876800 {#4974
       date: 2021-08-02 00:00:00.0 America/Toronto (-04:00),
     },
     Carbon\Carbon @1627963200 {#4978
       date: 2021-08-03 00:00:00.0 America/Toronto (-04:00),
     },
     Carbon\Carbon @1628049600 {#5007
       date: 2021-08-04 00:00:00.0 America/Toronto (-04:00),
     },
     Carbon\Carbon @1628136000 {#5009
       date: 2021-08-05 00:00:00.0 America/Toronto (-04:00),
     },
]

这是使用

dd($period->toArray());
的 Laravel 数据转储。如果您愿意,现在可以使用
$period
语句来迭代
foreach

一个重要说明 - 它包括提供给方法的两个边缘日期。

有关更多酷炫的约会相关内容,请查看 Carbon 文档


2
投票

有一个方法:

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

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

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

     $dtStart->addDay();
 }

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


2
投票

如果您使用的 php 版本低于 8.2 并且没有

DatePeriod::INCLUDE_END_DATE
const。我编写了一个返回
\DateTimeImmutable
数组的方法。

这适用于开始日期在结束日期之前、相同或之后。

    /**
     * @param DateTimeImmutable $start
     * @param DateTimeImmutable $end
     * @return array<\DateTimeImmutable>
     */
    public static function getRangeDays(\DateTimeImmutable $start, \DateTimeImmutable $end): array
    {
        $startDate = $start;
        $endDate = $end;
        $forwards = $endDate >= $startDate;
        $carryDate = $startDate;
        $days = [];
        while (true) {
            if (($forwards && $carryDate > $end) || (!$forwards && $carryDate < $end)) {
                break;
            }
            $days[] = $carryDate;

            if ($forwards) {
                $carryDate = $carryDate->modify('+1 day');
            } else {
                $carryDate = $carryDate->modify('- 1 day');
            }
        }

        return $days;
    }

2
投票

只是关于 while 循环的一个想法

$startDate = '2023-03-01';
$endDate = '2023-04-01';

$currentDate = strtotime($startDate);
$endDate = strtotime($endDate);

while ($currentDate <= $endDate) {
  echo date('Y-m-d', $currentDate) . "\n"; 
  $currentDate = strtotime('+1 day', $currentDate);
}

1
投票
$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"));
}

你也可以像这样迭代,

$_POST['date']
可以从你的应用程序或网站上凹下来 除了
$_POST['date']
,您还可以将字符串放置在此处
"21-12-2019"
。两者都会起作用。


1
投票
<?php

    $start_date = '2015-01-01';
    $end_date = '2015-06-30';

    while (strtotime($start_date) <= strtotime($end_date)) {
        echo "$start_daten";
        $start_date = date ("Y-m-d", strtotime("+1 days", strtotime($start_date)));
    }

?>

1
投票

我喜欢使用简单、干净且无库的方法,如下所示:

function datesBetween($startDate, $endDate)
{
    $dates = [];

    $start = new DateTime($startDate);
    $end = new DateTime($endDate);

    while ($start <= $end) {
        $dates[] = $start->format('Y-m-d');
        $start->modify('+1 day');
    }

    return $dates;
}

希望它对某人有帮助。


0
投票

如果你使用 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");
}

记得添加:

  • 使用碳\碳;
  • 使用Carbon\CarbonPeriod;

0
投票

更有弹性的例子



//dilo surucu

class Day
{
    private DateTimeInterface $dateTime;

    public function __construct(DateTimeInterface $dateTime)
    {
        $this->dateTime = $dateTime;
    }

    public function today(string $format='Y-m-d'): string
    {
        return $this->dateTime->format($format);
    }

    public function yesterday(string $format='Y-m-d'): string
    {
        $today = $this->today();
        return date($format, strtotime("$today -1 days"));
    }

    public function tomorrow(string $format='Y-m-d'): string
    {
        $today = $this->today();
        return date($format, strtotime("$today +1 days"));
    }
}

class DayIterator implements Iterator
{
    private DateTimeInterface $currentDate;
    private DateTimeInterface $endDate;

    /**
     * @throws Exception
     */
    public function __construct(string $startDate, string $endDate)
    {
        $this->currentDate = new DateTime($startDate);
        $this->endDate = new DateTime($endDate);
    }

    public function current(): Day
    {
        return new Day($this->currentDate);
    }

    public function key(): string
    {
        return $this->currentDate->format('Y-m-d');
    }

    public function next(): void
    {
        $this->currentDate = $this->currentDate->add(new DateInterval('P1D'));
    }

    public function rewind(): void
    {
    }

    public function valid(): bool
    {
        return $this->currentDate <= $this->endDate;
    }
}


// Usage
$dayIterator = new DayIterator(
    '2024-01-01',
    '2024-01-12'
);

foreach ($dayIterator as $day) {

    echo 'Yesterday: ' . $day->yesterday('D Y-m-d') . PHP_EOL;
    echo 'Date: ' . $day->today('D Y-m-d D') . PHP_EOL;
    echo 'Tomorrow: ' . $day->tomorrow('D Y-m-d') . PHP_EOL;
    echo PHP_EOL;
}

© www.soinside.com 2019 - 2024. All rights reserved.