【问题标题】:Laravel Carbon check if time is within the same minuteLaravel Carbon 检查时间是否在同一分钟内
【发布时间】:2017-11-06 23:11:54
【问题描述】:

我有来自数据库的日期时间和来自input='time' 字段的日期时间。

我有一个不带秒的日期时间(因此默认为 00)和一个带秒的日期时间。我需要检查这两个变量是否在同一分钟内。

示例:为真

Carbon {#349 ▼
  +"date": "2017-11-06 14:47:00.000000"
  +"timezone_type": 3
  +"timezone": "America/Chicago"
}
Carbon {#362 ▼
  +"date": "2017-11-06 14:47:44.000000"
  +"timezone_type": 3
  +"timezone": "America/Chicago"
}

例如:为假

Carbon {#349 ▼
  +"date": "2017-11-06 14:48:00.000000"
  +"timezone_type": 3
  +"timezone": "America/Chicago"
}
Carbon {#362 ▼
  +"date": "2017-11-06 14:47:44.000000"
  +"timezone_type": 3
  +"timezone": "America/Chicago"
}

我现在有这个,但它会在 60 秒内显示。如果它在同一分钟内,我很难显示。

$InsertTime = 2017-11-06 14:47
$DbTime = 2017-11-06 14:47:44


public function WithinMinCheck($InsertTime, $DbTime) {
   $WithinMin = "true";
   $InsertTime = Carbon::createFromFormat('Y-m-d H:i', $InsertTime);
   $DbTime = Carbon::createFromFormat('Y-m-d H:i:s', $DbTime);
   $difference = $InsertTime->diffInSeconds($DbTime);
   if ($difference >= 60) {
    $WithinMin = "false";
   } else {
    $WithinMin = "true";
   }

   return $WithinMin;
}

【问题讨论】:

    标签: php laravel datetime laravel-5


    【解决方案1】:

    您不能将第二个时间变量的第二个字段设置为 0 并比较值吗?

    $newTime = $DbTime->copy()->second(00);
    if($InsertTime->ne($newTime)) {
        $WithinMin = "false";
    }
    return $WithinMin;  //since $withinMin is set to true initially, it would only be false if Insertime is not equal
    

    请记住,上述解决方案仅在分钟值相同时才有效。如果第二次有不同的分钟值,即使在第一次的60秒内,也会返回false。

    【讨论】:

      【解决方案2】:

      为什么不将日期作为字符串进行比较?这很简单。

      $InsertTime = '2017-11-06 14:47';
      $DbTime = '2017-11-06 14:47:44';
      
      public function WithinMinCheck($InsertTime, $DbTime) {
         return (strpos($DbTime, $InsertTime) === 0);
      }
      

      【讨论】:

        猜你喜欢
        • 2018-08-15
        • 1970-01-01
        • 1970-01-01
        • 2021-06-29
        • 2019-10-24
        • 1970-01-01
        • 2018-04-07
        • 2018-01-29
        • 2020-09-16
        相关资源
        最近更新 更多