我以日期2010-05-01开始,以2010-05-10结束。如何在PHP中遍历所有这些日期?
当前回答
这里有一个方法:
$date = new Carbon();
$dtStart = $date->startOfMonth();
$dtEnd = $dtStart->copy()->endOfMonth();
$weekendsInMoth = [];
while ($dtStart->diffInDays($dtEnd)) {
if($dtStart->isWeekend()) {
$weekendsInMoth[] = $dtStart->copy();
}
$dtStart->addDay();
}
$weekendsInMoth的结果是周末天数的数组!
其他回答
用户本功能:-
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
这也包括最后的日期
$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");
}
如果你不需要最后的日期,只需从条件中删除=。
复制从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>";
}
如果你使用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");
}
记得加上:
使用碳\碳; 使用碳\ CarbonPeriod;
这里有一个方法:
$date = new Carbon();
$dtStart = $date->startOfMonth();
$dtEnd = $dtStart->copy()->endOfMonth();
$weekendsInMoth = [];
while ($dtStart->diffInDays($dtEnd)) {
if($dtStart->isWeekend()) {
$weekendsInMoth[] = $dtStart->copy();
}
$dtStart->addDay();
}
$weekendsInMoth的结果是周末天数的数组!
推荐文章
- PHP中的三个点(…)是什么意思?
- Guzzlehttp -如何从guzzle6得到响应的正文?
- 移动一个文件到服务器上的另一个文件夹
- Laravel中使用雄辩的ORM进行批量插入
- PHP 5.4调用时引用传递-容易修复可用吗?
- 格式化字节到千字节,兆字节,千兆字节
- 如何在PHP中获得变量名作为字符串?
- 如何减去日期/时间在JavaScript?
- 用“+”(数组联合运算符)合并两个数组如何工作?
- Laravel PHP命令未找到
- 如何修复从源代码安装PHP时未发现xml2-config的错误?
- 在PHP中对动态变量名使用大括号
- 将Date对象转换为日历对象
- 如何从对象数组中通过对象属性找到条目?
- 如何从关联数组中删除键及其值?