如何在Laravel中添加日期和时间来获取DateTime?

时间:2014-08-31 09:08:52

标签: laravel

我的数据库中有两列:日期和时间。我想将它们组合到DateTime中,以便我可以使用diff()来获得当前时间和组合DateTime之间的差异。

3 个答案:

答案 0 :(得分:0)

$query = DB::query("select concat(date," ",time) as datetime from TABLENAME");使用此行查询,您可以连接日期和时间DB值;它会像日期时间值一样工作。

答案 1 :(得分:0)

你可以使用mutators:

// assuming your date field is in format Y-m-d and time H:i:s
// and you want the property named someTimestamp

public function getSomeTimestampAttribute()
{
  // use Carbon\Carbon for the class
  return new Carbon($this->attributes['date'] . ' ' . $this->attributes['time']);
}

public function setSomeTimestampAttribute($dateTime)
{
  // parse param to get string 'Y-m-d H:i:s'
  $dateTime = $this->fromDateTime($dateTime);

  $date = substr($dateTime, 0, 10); // Y-m-d
  $time = substr($dateTime, 11);  // H:i:s

  $this->attributes['date'] = $date;
  $this->attributes['time'] = $time;
}

然后你可以这样做:

// get
$model->someTimestamp; // Carbon instance depending on date & time db fields
$model->someTimestamp->diff(Carbon::now());

// set - all methods do the same
$model->someTimestamp = new Carbon('2014-08-31 11:55:00');
$model->someTimestamp = new DateTime('2014-08-31 11:55:00');
$model->someTimestamp = '2014-08-31 11:55:00';

// then this is true
$model->date; // 2014-08-31
$model->time; // 11:55:00
// so you can now call ->save() on the model and values in db will be correct

答案 2 :(得分:0)

连接两个变量存储是不够的,它需要更多。我正在使用Laravel,所以在我的情况下,这就是诀窍:

    $datetime = $date.' '.$time;
    $datetime = new DateTime($datetime);

我需要的只是一个DateTime对象,这就是我得到它的方式。所以在此之后我可以很容易地得到两个DateTime对象之间的区别。

    $currentDateTime = new DateTime(); //Returns current time & date in a DateTime object
    $difference = $currentDateTime->diff($datetime);

$差异就是我想要的一切。