将字符串转换为datetime php不按预期返回

时间:2016-12-17 15:15:06

标签: php mysql laravel datetime

在我的应用程序中,我从表单中获取了分隔的日期和时间值,然后我将它们连接起来,将其传递给一个转换为php中的DateTime对象的方法。问题是,当我调用函数 DateTime :: createFromFormat 时,它会在我尝试作为datetime mysql数据类型插入后立即返回零值。代码是:

public function store(Request $request)
{

    $this->validate($request, array(
        'titulo' => 'required|max:255',
        'descr' => 'required|max:255',
        'cidade' => 'required|max:255',
        'rua' => 'required|max:255',
        'bairro' => 'required|max:255',
        'nro' => 'required|numeric'
    ));

    $dataInic = \DateTime::createFromFormat('d-m-Y H:i', 
            $request->input('diaInic') . "-" .
            $request->input('mesInic') . "-" .
            $request->input('anoInic') . " " .
            $request->input('horaInic') . "-" .
            "0" . $request->input('minutoInic') . "-"
            );
    //$dataInicInput = $dataInic->format('Y-m-d H:i');

    $dataFim = \DateTime::createFromFormat('d-m-Y H:i', 
            $request->input('diaFinal') . "-" .
            $request->input('mesFinal') . "-" .
            $request->input('anoFinal') . " " .
            $request->input('horaFinal') . "-".
            $request->input('minutoFinal') . "-"
            );
    //$dataFimInput = $dataFim->format('Y-m-d H:i');

    //creates the model to insert in mysql db
    $event = new Event;

    $event->titulo = $request->titulo;
    $event->descr = $request->descr;
    $event->cidade = $request->cidade;
    $event->rua = $request->rua;
    $event->bairro = $request->bairro;
    $event->nro = $request->nro;
    $event->horarioinic = $dataInic;
    $event->horariofim = $dataFim;

    $event->save(); 

    Session::flash('success','O evento foi salvo com sucesso!');

    return redirect()->route('pages.agenda');
}

根据api.jqery.com格式d-m-Y H:i似乎是正确的,因为输入的连接产生的字符串如:22-12-2016 15-301-2-2016 2-5

1 个答案:

答案 0 :(得分:2)

由于您使用的是Laravel,因此您可以使用Carbon

Carbon::parse($dateTimeString);