【问题标题】:PHP - Fetch all dates between two dynamic UNIX timestamps [duplicate]PHP - 获取两个动态 UNIX 时间戳之间的所有日期 [重复]
【发布时间】: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 没问题。但我仍然得到空数组

标签: php laravel date


【解决方案1】:

终于找到了这个问题的答案。它通过将日期转换为 UNIX 时间戳来工作。这是代码,它是如何工作的:

$date_from = "2018-07-01";   
$date_from = strtotime($date_from); // Convert date to a UNIX timestamp  

// Specify the end date. This date can be any English textual format  
$date_to = strtotime(today()); // Convert date to a UNIX timestamp  

$dates = [];

// Loop from the start date to end date and output all dates inbetween  
for ($i=$date_from; $i<=$date_to; $i+=86400) {  
    array_push($dates,date("Y-m-d", $i));  
}

return $dates;

Here 是我找到此解决方案的参考,希望这对其他人也有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-28
    • 2014-05-22
    • 1970-01-01
    • 2011-02-26
    • 1970-01-01
    • 2015-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多