[英]I have 2 time in PHP, how can I run a foreach loop to go through all of those days? (1 Hour loop same time Last 24 Hours!)
[英]I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?
我从日期2010-05-01
开始,以2010-05-10
结束。 我如何在 PHP 中遍历所有这些日期?
$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 个。 您可以根据自己的喜好调整格式。 请参阅DatePeriod的 PHP 手册。 它需要 PHP 5.3。
这也包括最后日期
$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");
}
如果您不需要最后日期,只需从条件中删除=
。
转换为 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 的时间,以防止跳过或重复天数。
从包含范围的 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>";
}
$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);
这是另一个简单的实现 -
/**
* 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
)
使用此功能:-
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
这是一种方法:
$date = new Carbon();
$dtStart = $date->startOfMonth();
$dtEnd = $dtStart->copy()->endOfMonth();
$weekendsInMoth = [];
while ($dtStart->diffInDays($dtEnd)) {
if($dtStart->isWeekend()) {
$weekendsInMoth[] = $dtStart->copy();
}
$dtStart->addDay();
}
$weekendsInMoth 的结果是周末天数的数组!
$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"
。 两者都会起作用。
<?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)));
}
?>
如果您使用的 php 版本低于 8.2,并且没有DatePeriod::INCLUDE_END_DATE
常量。 我写了一个返回\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;
}
如果您使用 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
用户$startDay = Carbon::parse("2021-08-01");
$endDay= Carbon::parse("2021-08-05");
$period = $startDay->range($endDay, 1, 'day');
当我打印数据时
array:5 [▼
0 => Carbon\Carbon @1627776000 {#1290 ▼
#endOfTime: false
#startOfTime: false
#constructedObjectId: "0000000045f68b6a0000000030c488c5"
#localMonthsOverflow: null
#localYearsOverflow: null
#localStrictModeEnabled: null
#localHumanDiffOptions: null
#localToStringFormat: null
#localSerializer: null
#localMacros: null
#localGenericMacros: null
#localFormatFunction: null
#localTranslator: null
#dumpProperties: array:3 [▶]
#dumpLocale: null
date: 2021-08-01 00:00:00.0 UTC (+00:00)
}
1 => Carbon\Carbon @1627862400 {#1291 ▼
#endOfTime: false
#startOfTime: false
#constructedObjectId: "0000000045f68b6b0000000030c488c5"
#localMonthsOverflow: null
#localYearsOverflow: null
#localStrictModeEnabled: null
#localHumanDiffOptions: null
#localToStringFormat: null
#localSerializer: null
#localMacros: null
#localGenericMacros: null
#localFormatFunction: null
#localTranslator: null
#dumpProperties: array:3 [▶]
#dumpLocale: null
date: 2021-08-02 00:00:00.0 UTC (+00:00)
}
2 => Carbon\Carbon @1627948800 {#1292 ▶}
3 => Carbon\Carbon @1628035200 {#1293 ▶}
4 => Carbon\Carbon @1628121600 {#1294 ▶}
]
这是使用dd($period->toArray());
period- dd($period->toArray());
Laravel 数据转储dd($period->toArray());
. 如果需要foreach
语句,您现在可以遍历$period
。
一个重要的注意事项- 它包括提供给方法的边缘日期。
有关更酷的日期相关内容,请查看Carbon 文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.