Cody Short Cody Short - 1 month ago 5
HTML Question

Setting time input to datetime from database

I'm currently retrieving data from a database over an API. The data comes back in this format:

2016-10-12T08:00:00


I would like to display the time portion of this in a time input field with AM and PM on my current webpage.

I have the following input:



<input type="time" name="StartTime" class="form-control" />





When the ajax call finishes successfully to the api i do the following:



$("#group-management #EditGroupModal [name=StartTime]").val(data.startTime);





data.StartTime is of course the string of datetime text seen above.

Which currently does not set the value of the time input on the page. I'm guessing it is because there is some formatting issue. I would like to parse the text string seen above and put it into the form field on the front end, but I am unsure of how to go about doing it. I have tried playing around with the Date object but no luck.

Answer

The time input only accepts a time as a valid value, as in 08:00:00

You can split your string, and pop of the time

var data = {startTime : "2016-10-12T08:00:00"}

var time = data.startTime.split('T').pop();

$("[name=StartTime]").val(time);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="time" name="StartTime" class="form-control" />

Comments