25

我想将时间戳存储在数据库中,时间组件为00:00:00.
以下代码:

$start_date = Carbon::createFromFormat('d-m-Y', $date_interval["start_date"]); 
$end_date = Carbon::createFromFormat('d-m-Y', $date_interval["end_date"]); 

当我只提供没有时间指定的日期时,将当前时间添加到日期。
我需要这个,因为之后我需要从数据库中检索内部整数,这应该是一天的开始。

存储这个“一天的开始”的最佳方式是什么?

4

4 回答 4

36

为了安全起见,让 Carbon 使用->endOfDay()or来决定一天的结束或开始->startOfDay()。选择更适合你的。

Carbon::createFromFormat('d-m-Y', $date_interval["start_date"])->endOfDay();
Carbon::createFromFormat('d-m-Y', $date_interval["start_date"])->startOfDay();
于 2017-08-13T05:34:01.387 回答
33

我通常会设置通话日期,然后将时间重置为 00:00

Carbon::setTime(0, 0, 0);  // from the parent, DateTime class

在该类中,还有一个 Carbon::startOfDay() 方法将设置适当的值。

public function startOfDay()
{
    return $this->hour(0)->minute(0)->second(0);
}
于 2014-12-29T19:02:16.847 回答
1

Carbon::createFromFormat() differs from its parent, in that missing parts are set to the current date or time instead of zero. In order to make it behave like \DateTime::createFromFormat(), use the | or ! format characters, as described in the manual (https://www.php.net/manual/en/datetime.createfromformat.php).

Example:

$midnight = Carbon::createFromFormat(
    'Y-m-d|', // or: '!Y-m-d'
    $date
);
于 2019-11-27T14:41:39.693 回答
0

你不应该那样做。

设置你的start_dateDATE NULL DEFAULT NULL`

你应该让 MySQL 默认为 NULL 不0000-00-00

于 2014-12-29T17:39:33.177 回答