Problem with Laravel date

Asked

Viewed 3,257 times

3

My problem is in the date conversion, see:

echo date('Y-m-d', strtotime(Input::get('data_evento')));

echo of Input::get('data_evento'): 14/02/2014

echo of date('Y-m-d', strtotime(Input::get('data_evento'))): 1969-12-31

I really don’t know what’s going on.

  • The field data_evento is being set? What values are coming from the form posting?

  • @rodrigorigotti is in doubt the value coming from the form is 14/02/2014 and to store in the bank would have to stay 2014-02-14

  • If it is coming as "14/02/2014", the strtotime will not understand the format and gives an invalid date (Unix time = -1, ie "31/12/1969"). What you can do is submit the date in YYYY-MM-DD format or change the date format after it was submitted.

  • From a read on: https://github.com/briannesbitt/Carbon great tool for date manipulation, everything you need one day is there. p. s: native

3 answers

5


With pure php in version 5.3 utlize createFromFormat of Datetime to convert the format of dd/mm/Y for Y-mm-dd(bank format)

$data = '14/02/2014';
$data_formatada = DateTime::createFromFormat('d/m/Y', $data);
echo $data_formatada->format('Y-m-d') ."<br>";
  • Exactly the solution of the problem, thank you very much

2

Another option is to use the `Carbon Carbon library, created by Brian Nesbitt.

She comes installed by default in Laravel. She is a class improvement DateTime quoted above.

\Carbon\Carbon::createFromFormat('d/m/Y', $data);

Documentation http://carbon.nesbot.com/

-1

I have a function for that, might be useful to someone.

function date_fmt_back(?string $date): ?string {
  if (!$date) {
     return null;
  }

  if (strpos($date, " ")) {
    $date = explode(" ", $date);
    return implode("-", array_reverse(explode("/", $date[0]))) . " " . $date[1];
  }

  return implode("-", array_reverse(explode("/", $date)));
}
  • 1

    If I pass an invalid date, example > 14/13/2021 will return 2021-13-14. Createfromformat cited in the above posts serve much better and if for example, using the same date 14/13/2021 the method will return the next month 2022-01-14 or if send the date 32/11/2021 the method returns 2021-12-02, ie, returns the date with the months/days "sent more"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.