【问题标题】:Laravel carbon failed to parse time stringLaravel carbon 无法解析时间字符串
【发布时间】:2017-09-02 03:28:40
【问题描述】:

我需要从模型用户中选择特定年龄的用户,但是出现这个错误:

DateTime::__construct(): Failed to parse time string (birth) at position 0 (b): The timezone could not be found in the database 

部分控制器:

$users = User::where(Carbon::parse('birth')->diff(Carbon::now())->format('%y'), '>=', 18)->get();

当我使用它查看所有工作正常时:

 @foreach ($userss as $user)

 <?php  $age_year = Carbon::parse($user->birth)->diff(Carbon::now())->format('%y'); ?>


@endforeach

感谢您的回答!

【问题讨论】:

  • 我认为日期时间格式问题

标签: php laravel php-carbon


【解决方案1】:

在您的控制器示例中,您尝试解析字符串 'birth' 而不是数据库字段 'birth'。

由于您要返回一个集合,只需使用 filter() 方法遍历返回的集合,然后再将其发送到您的视图。你也可以使用 age 属性而不是做一个 diff

$users = User::get()->filter(function($user, $key) {
    return (Carbon::parse($user->birth)->age >= 18);
});

我没有对此进行测试,因此您可能会遇到一些拼写错误,但这就是您想要完成此任务的方式。

【讨论】:

  • 谢谢,就是这样。缺少函数:$users = $users_all->filter(function ($patients, $key) { return (Carbon::parse($user->birth)->age >= 18); });
  • 谢谢。我添加了函数声明
【解决方案2】:

试试这个:

User::where('birth','>=', Carbon::now()->subYears(18)->toDateTimeString());

尚未测试,但希望它有效!

【讨论】:

    【解决方案3】:

    您可以使用Carbondiff 助手来计算年龄,并使用filter 方法过滤对象(本例中为User)。

    $users = User::get()->filter($user, $key) {
        return Carbon\Carbon::now()->diff($user->birth)->y >= 18;
    });
    

    Carbon 还提供其他帮助函数,其中一些是:

    // diffInYears(), diffInMonths(), diffInWeeks()
    // diffInDays(), diffInWeekdays(), diffInWeekendDays()
    // diffInHours(), diffInMinutes(), diffInSeconds()
    

    请查看此内容以获取更多信息: http://carbon.nesbot.com/docs/

    【讨论】:

      猜你喜欢
      • 2021-08-27
      • 2019-11-08
      • 1970-01-01
      • 1970-01-01
      • 2013-07-14
      • 1970-01-01
      • 2019-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多