Laravel carbon 解析时间字符串失败
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/45649128/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel carbon failed to parse time string
提问by Yrtymd
I need to select users with specific age from model User, but have this error:
我需要从模型用户中选择具有特定年龄的用户,但出现此错误:
DateTime::__construct(): Failed to parse time string (birth) at position 0 (b): The timezone could not be found in the database
part of controller:
控制器的一部分:
$users = User::where(Carbon::parse('birth')->diff(Carbon::now())->format('%y'), '>=', 18)->get();
when i use it in view all working fine:
当我使用它查看所有工作正常时:
@foreach ($userss as $user)
<?php $age_year = Carbon::parse($user->birth)->diff(Carbon::now())->format('%y'); ?>
@endforeach
Thanks for answers!
感谢您的回答!
回答by Rob Fonseca
In your controller example, you are trying to parse the string 'birth'instead of the database field 'birth'.
在您的控制器示例中,您试图解析字符串“birth”而不是数据库字段“birth”。
Since you are returning a collection, just run through the returned collections with the filter() method before sending it down to your view. You can also use the ageproperty instead of doing a diff
由于您正在返回一个集合,因此只需在将其发送到您的视图之前使用 filter() 方法运行返回的集合。您还可以使用age属性而不是进行 diff
$users = User::get()->filter(function($user, $key) {
return (Carbon::parse($user->birth)->age >= 18);
});
I did not test this, so you may get some typos, but this is how you will want to accomplish this task.
我没有测试这个,所以你可能会得到一些拼写错误,但这就是你想要完成这个任务的方式。
回答by Vynart
try this:
尝试这个:
User::where('birth','>=', Carbon::now()->subYears(18)->toDateTimeString());
not tested yet, but hope it works!
尚未测试,但希望它有效!
回答by M_Idrees
You can use Carbon
's diff
helper to calculate age, and filter
method to filter objects(User
in this case).
您可以使用Carbon
's diff
helper 来计算年龄,并使用filter
方法来过滤对象(User
在这种情况下)。
$users = User::get()->filter($user, $key) {
return Carbon\Carbon::now()->diff($user->birth)->y >= 18;
});
There are also other helpers functions available with Carbon
, some are:
还可以使用其他辅助函数Carbon
,其中一些是:
// diffInYears(), diffInMonths(), diffInWeeks()
// diffInDays(), diffInWeekdays(), diffInWeekendDays()
// diffInHours(), diffInMinutes(), diffInSeconds()
Please review this for more information: http://carbon.nesbot.com/docs/
请查看此以获取更多信息:http: //carbon.nesbot.com/docs/