How to convert string from input type="datetime-local" to datetime in symfony without FormBundle?

546 Views Asked by At

I have date with time string: array(2) { ["available_from"]=> string(16) "2020-07-30T12:26" ["available_to"]=> string(16) "2020-07-30T23:32" }

Input:

<div class="col-lg-3 col-sm-6 col-xs-12">
    <label>Ważna od:</label>
    <input type="datetime-local" id="availableDateFrom" name="date[available_from]" class="datetimepicker required"
           data-min-date="{{ 'now'|date('Y-m-d') }}"
           value="{% if available_offer_hours.availableFrom is defined %}{{ available_offer_hours.availableFrom }}{% else %}{{ 'now'|date("Y-m-d") }} 00:00{% endif %}"/>
</div>
<div class="col-lg-3 col-sm-6 col-xs-12">
    <label>Ważna do:</label>
    <input type="datetime-local" id="availableDateTo" name="date[available_to]" class="datetimepicker required"
           data-min-date="{{ 'now'|date('Y-m-d') }}"
           value="{% if available_offer_hours.availableTo is defined %}{{ available_offer_hours.availableTo }}{% else %}{{ 'now'|date("Y-m-d") }} 15:45{% endif %}"/>
</div>

I use form method POST and get the value in controller by: $request->request->get('date').
This one of example from unsuccessful attempts:

$availableDate = [
     'available_from' => date_create($request->request->get('date[available_from]')),
     'available_to' => $this->changeDateTimezone($request->request->get('date[available_to]'))
   ];
var_dump($availableDate);

Everytime when i try to use: \DateTime::createFromFormat, new \DateTime(string ), strtotime(), etc. i got bool(false), actual datetime or datetime from year above 1970 - but not converted string to object dateTime from input name="date[available_form]".

I need help how to do it properly - (get DateTime object from string value: "date[available_from]") / what i'm doing wrong?

Thanks.

1

There are 1 best solutions below

2
On

This is just a wild guess but you are probably missing the 'T' when parsing the datestrings, T is just a separator in this place, unluckily you did not provide any trys but this could work:

$str = "2020-07-30T23:32" ;
$dt = DateTime::createFromFormat("Y-m-d\TH:i", $str);
echo $dt->format("d.m.Y H:i");

outputs for me:

30.07.2020 23:32