【问题标题】:How to calculate hour intervals from two datetimes in PHP?如何从 PHP 中的两个日期时间计算小时间隔?
【发布时间】:2017-07-14 07:41:32
【问题描述】:

我正在创建一个在线预订系统。当用户单击日历中的日期时,它会返回该日期的两个日期时间(开始和结束)。我正在尝试计算我能够做到的从开始到结束的所有小时数,但我需要以间隔显示小时数。

假设用户添加了明天 10.00-14.00 的可用时间,那么我需要像这样显示时间:

10.00-11.00

11.00-12.00

12.00-13.00

13.00-14.00

特定日期。

到目前为止我所拥有的。

public function getTimes()
{

  $user_id = Input::get("id"); //get the user id
  $selectedDay = Input::get('selectedDay');   // We get the data from AJAX for the day selected, then we get all available times for that day
  $availableTimes = Nanny_availability::where('user_id', $user_id)->get();

  // We will now create an array of all booking datetimes that belong to the selected day
  // WE WILL NOT filter this in the query because we want to maintain compatibility with every database (ideally)

  // For each available time...
  foreach($availableTimes as $t => $value) {
    $startTime = new DateTime($value->booking_datetime);

    if ($startTime->format("Y-m-d") == $selectedDay) {
      $endTime = new DateTime($value->booking_datetime);

      date_add($endTime, DateInterval::createFromDateString('3600 seconds'));

      // Try to grab any appointments between the start time and end time
      $result = Nanny_bookings::timeBetween($startTime->format("Y-m-d H:i"), $endTime->format("Y-m-d H:i"));

      // If no records are returned, the time is okay, if not, we must remove it from the array
      if($result->first()) {
        unset($availableTimes[$t]);
      }

    } else {
      unset($availableTimes[$t]);
    }
  }

  return response()->json($availableTimes);
}

我怎样才能得到间隔?

【问题讨论】:

    标签: php datetime


    【解决方案1】:

    根据您的问题,假设开始和结束之间的小时差为 1,您可以使用 DateIntervalDatePeriod 来迭代时间,例如:

    $startDate = new DateTime( '2017-07-18 10:15:00' );
    $endDate = new DateTime( '2017-07-18 14:15:00' );
    $interval = new DateInterval('PT1H'); //interval of 1 hour
    $daterange = new DatePeriod($startDate, $interval ,$endDate);
    
    $times = [];
    foreach($daterange as $date){
        $times[] = $date->format("H:i") . " -- " 
            . $date->add(new DateInterval("PT1H"))->format("H:i");
    }
    echo "<pre>"; print_r($times);
    //gives
    Array
    (
        [0] => 10:15 -- 11:15
        [1] => 11:15 -- 12:15
        [2] => 12:15 -- 13:15
        [3] => 13:15 -- 14:15
    )
    

    更新

    您可以使用json_encode() 来返回 json 时间数据,如:

    $jsonTimes = json_encode($times);
    

    【讨论】:

    • 它使用普通的 php。你能给我一个例子如何将日期返回为 json 吗?
    • @raqulka 您可以将 json_encode() 用于 $times 数组,以在更新的答案中返回 json 数据
    • 赏金是你的,先生。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2021-10-09
    • 2015-06-19
    • 1970-01-01
    • 2014-03-08
    • 2012-01-31
    • 2020-06-28
    • 1970-01-01
    相关资源
    最近更新 更多