【发布时间】:2018-08-11 05:50:01
【问题描述】:
我想获取两个给定特定日期之间的所有日期,这些日期将根据用户要求动态变化。
这对我来说很好用:
$begin = new DateTime( '2018-07-01' );
$end = new DateTime( '2018-08-10' );
$end = $end->modify( '+1 day' );
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
$dates = [];
foreach($daterange as $date){
array_push($dates,$date->format('Y-m-d'));
}
return $dates;
但是当我动态插入日期时,这给了我 NULL 数组。例如,
$begin = new DateTime($request->date1);
$end = new DateTime(today());
$interval = new DateInterval('P1D');
$daterange = new DatePeriod($begin, $interval ,$end);
$dates = [];
foreach($daterange as $date){
array_push($dates,$date->format('Y-m-d'));
}
return dates;
我尝试了许多输入,例如将今天的日期存储在变量中,更改其格式,然后使用该变量作为输入。我尝试使用 (string) 函数将日期变量更改为字符串,并且我也使用了 Carbon 类作为日期,但不知何故我在使用 DateTime、DateInterval 和 DatePeriod 时犯了错误,因为我不知道它们的基础知识。
我需要在我的管理面板中获取图表的两个特定日期之间的所有日期。
【问题讨论】:
-
检查
$request->date1的格式并调试echo $begin&echo $end等代码 -
先生,我试过这个 $present = Carbon::now()->toDateString();然后 $begin = new DateTime( $present );但我收到此错误{msg:“类 DateTime 的对象无法转换为字符串 32”,状态:0},即使没有 toDateString 函数,我也会收到同样的错误。
-
如果你有空数组,可能是因为你的时间间隔大于你的开始日期和结束日期之间的差距......你需要检查是否 $start!==$end 和$end-$start>间隔...
-
我查过了,$interval 没问题。但我仍然得到空数组