简体   繁体   English

Laravel 4 Eloquent-时间戳超过3年

[英]Laravel 4 Eloquent - where timestamp is over 3 years old

I have a field called RegistrationDate which I need to check for time since. 我有一个称为RegistrationDate的字段,此后我需要检查时间。

I need a where claus that will do: 我需要一个可以做到的地方:

if (time() - strtotime($car->RegistrationDate) > 3*365.25*24*60*60)
    over 3 years old
}

So: 所以:

$cars::where('RegistrationDate', '>', '3 years old')->get();

but don't know how to do that, my dates are saved as timestamps: 2009-07-17 00:00:00. 但不知道该怎么做,我的日期已另存为时间戳记:2009-07-17 00:00:00。

thanks. 谢谢。

Use the Carbon Library. 使用碳库。 I think it is loaded by the laravel framework already. 我认为它已经由laravel框架加载。 But if not you can load via composer. 但是,如果没有,您可以通过作曲家加载。 https://github.com/briannesbitt/Carbon https://github.com/briannesbitt/Carbon

$cars::where('RegistrationDate', '>', Carbon\\Carbon::now()->subYears(3))->get(); Assuming $cars is an eloquent object for your Car model; 假设$cars是您的Car模型的雄辩对象;

Also, unrelated to question... but your table naming conventions are a bit weird. 另外,与问题无关...但是您的表命名约定有点奇怪。

$cars = Car::where('registration_date', '>', Carbon\\Carbon::now()->subYears(3))->get();

You can also use DateTime and DateTimeInterval class: 您还可以使用DateTimeDateTimeInterval类:

$currentDate = new DateTime(); // get current date time
$currentDate->sub(new DateInterval('P3Y')); // substract 3 years from current date 

After that you can use $currentDate in your code like: 之后,您可以在代码中使用$currentDate ,例如:

$cars::where('RegistrationDate', '>', $currentDate)->get();

You can also convert $currentDate to sql datetime string you needed with: 您还可以使用以下方法将$currentDate转换$currentDate所需的sql datetime字符串:

$currentDateStr = $currentDate->format('Y-m-d H:i:s');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM