2

I would like to set the value of an input:datetime-local field in Blade with data from the database but it only shows a blank placeholder values.

Below is my attempt which is not working:

<input type="datetime-local" value="{{ date('d/m/YH:i', strtotime($slider->run_to)) }}">

In my research, I have found out that the field needs value in this format YYYY-MM-DDTHH:MM or like in my case d/m/YTH:i where T is a string literal.

My problem is I am not able to find a way to do this in Laravel-Blade with dynamic data.

Is there any way to achieve it? If not then what alternatives are there for displaying date time in an input field?

medilies
  • 1,811
  • 1
  • 8
  • 32
The Only Smart Boy
  • 578
  • 19
  • 39

1 Answers1

1

The format of datetime-local value format isn't similar to what we see on the browser by default.

... the displayed date and time formats differ from the actual value; the displayed date and time are formatted according to the user's locale as reported by their operating system, whereas the date/time value is always formatted YYYY-MM-DDThh:mm.


I'll replace your $slider->run_to with the valid datetime '2022-03-17 23:59:26' to provide my solution

<input type="datetime-local" value="{{ substr(date('c', strtotime('2022-03-17 23:59:26')), 0, 16) }}">
  1. I used to format character c that stands for ISO 8601 date which outputs '2022-03-17T23:59:26+01:00'.
  2. I did cutout the seconds and the UTC offset ':26+01:00'
  • Note that allowing the seconds with substr $length of 19 wouldn't break the element.

enter image description here

enter image description here

Demo: https://3v4l.org/aMpMN


Another alternative solution that includes seconds:

<input type="datetime-local" value="{{ str_replace(' ', 'T', '2022-03-17 23:59:26') }}">

enter image description here

Demo: https://3v4l.org/710EN

medilies
  • 1,811
  • 1
  • 8
  • 32
  • 1
    The second alternative worked while the first did not, I'm researching on the reason why and will update my comment to help anyone who may have the same problem in future – The Only Smart Boy Mar 21 '22 at 06:10
  • @TheOnlySmartBoy Show me the value of `$slider->run_to` and `date('c', strtotime($slider->run_to))` – medilies Mar 21 '22 at 18:46