【问题标题】:Validate Date and Time in the Laravel Model在 Laravel 模型中验证日期和时间
【发布时间】:2016-09-04 16:37:18
【问题描述】:

我有一个日期选择器插件来弹出一个日历视图以允许用户选择日期+时间,但是它产生的格式是:

May 9, 2016 8:30 AM

存储到数据库时,我需要的格式是:

2016-09-05 08:30:00

在我的应用程序的控制器中,我有:

public function save(Request $request)
{
    Entry::create($request->all());
    return redirect('entries');
}

这会保存用户的表单输入,但由于格式不正确,它不会保存日期时间。我尝试创建一个新函数来格式化日期,然后再将其输入数据库。

public function formatDate($data)
{
    $returnDate = DateTime::createFromFormat('Y-d-m G:i:s', $data);
    return $returnDate->format('Y-d-m G:i:s');
}

但是,当我从保存函数调用该函数时,它显示未定义函数。我是不是做错了什么,或者实现这一目标的正确方法是什么?

【问题讨论】:

  • $returnDate = DateTime::createFromFormat('Y-d-m G:i:s', $data);这里 $returnDate 返回 false.so 发生错误

标签: php laravel datetime format


【解决方案1】:

例如;

$data = "May 9, 2016 8:30 AM";

return  date('Y-d-m H:i:s',strtotime($data));

【讨论】:

    【解决方案2】:

    在 Laravel 中,created_at 和 updated_at 被转换为 Carbon 对象

    https://laravel.com/docs/5.2/eloquent-mutators#date-mutators

    有了你的约会,你可以做同样的事情

    class User extends Model { /** * The attributes that should be mutated to dates. * * @var array */ protected $dates = ['created_at', 'updated_at', 'your_date']; }

    然后,当保存日期时,它将被转换为正确的格式。

    试一试,让我们知道你的进展如何!

    【讨论】:

      【解决方案3】:

      这两个函数都在模型内部? 如果是这样,您是如何尝试调用 formatDate 函数的?

      你可以改用匿名函数,试试:

      $formatted_date = function() use ($data) { $returnDate = DateTime::createFromFormat('Y-d-m G:i:s', $data); return $returnDate->format('Y-d-m G:i:s'); };

      在您的控制器或模型中。

      【讨论】:

      • 两个函数在同一个模型中。我尝试在 save 函数中调用 formatDate,但它声明函数未定义,因此我上面的代码不包含它,我仍在尝试使用它。感谢您的回复。
      【解决方案4】:

      您必须为DateTime::createFromFormat() 设置正确的格式。从格式创建意味着,您必须告诉模式以匹配给定日期中的任何信息。对于您的约会,模式是:

      DateTime::createFromFormat('F j, Y g:i A', $data);
      

      这是一个演示:https://eval.in/567629

      所有格式选项的列表:http://php.net/manual/en/function.date.php

      【讨论】:

        猜你喜欢
        • 2016-04-26
        • 2019-04-21
        • 2012-04-14
        • 1970-01-01
        • 1970-01-01
        • 2023-03-26
        • 2020-03-07
        • 2021-06-01
        • 2021-03-17
        相关资源
        最近更新 更多