代码之家  ›  专栏  ›  技术社区  ›  Shreeraj

PHP-获取两个动态用户输入日期之间的所有日期[重复]

  •  1
  • Shreeraj  · 技术社区  · 6 年前

    我想得到两个特定日期之间的所有日期,这些日期将根据用户需求动态变化。

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

    但当我动态插入日期时,这给了我空数组。例如,

    $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时出错了,因为我不知道它们的基本知识。

    1 回复  |  直到 6 年前
        1
  •  2
  •   Shreeraj    6 年前

    终于找到了这个问题的答案。它通过将日期转换为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 是我找到这个解决方案的参考,希望这对其他人也有帮助。