I have datetime-local html control on my form and I need to set date and time on it dynamically via JS or jQuery. How can I do it?
<input type="datetime-local" id="publishDate" required/>
I tried
$("#publishDate").val("2013-3-18 13:00"); $("#publishDate").val("2013-3-18T13:00"); $("#publishDate").val(new Date().toLocalString());
but nothing worked.
If the time zone is not important to your application, use datetime-local. Some browsers are still trying to catch up to the datetime input type. Firefox 7 has still not shown any progress in this area. Instead, set up your own using three select fields with options that are populated in relation to today's date.
In JavaScript, we can easily get the current date or time by using the new Date() object. By default, it uses our browser's time zone and displays the date as a full text string, such as "Fri Jun 17 2022 10:54:59 GMT+0100 (British Summer Time)" that contains the current date, time, and time zone.
This would do the trick
$("#publishDate").val("2013-03-18T13:00");
You need to use 2 digits for the month to make your sample work.
If you want to set the current date, then you can try this:
__Method 1:__ $(document).ready(function(){ $('input[type=datetime-local]').val(new Date().toJSON().slice(0,19)); }); __Method 2:__ function zeroPadded(val) { if (val >= 10) return val; else return '0' + val; } $(document).ready(function(){ d = new Date(); $('input[type=datetime-local]').val(d.getFullYear()+"-"+zeroPadded(d.getMonth() + 1)+"-"+zeroPadded(d.getDate())+"T"+d.getHours()+":"+d.getMinutes()+":"+d.getSeconds()); });
Note: You can replace $('input[type=datetime-local]') with Id
or Name
or Class
of the datetime-local field.
EDIT: d.getMonth() returns a value between 0-11, so to input the proper month 1 needs to be added to the result.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With