2

In my application, I'm getting separated date and time values from a form and then I concatenate them to pass it to a method which converts to a DateTime object in php. The problem is that when I call the function DateTime::createFromFormat, it returns a zero giving an error right after when I try to insert as a datetime mysql datatype. The code is:

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');
}

According to the documentation the format d-m-Y H:i seems to be right since the concatenations of the inputs is generating strings like: 22-12-2016 15-30 and 1-2-2016 2-5.

1
  • 2
    The correct format for dates in MySQL is the ISO 8601 format: YYYY-MM-DD. Commented Dec 17, 2016 at 15:18

1 Answer 1

2

Since you're using Laravel, you can use Carbon for this:

Carbon::parse($dateTimeString);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.