Setting default value for a datetime-local input field in Blade

1.7k Views Asked by At

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?

1

There are 1 best solutions below

2
medilies On BEST ANSWER

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