Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set datetime on datetime-local via jQuery

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.

like image 395
Vlad Bezden Avatar asked Mar 18 '13 19:03

Vlad Bezden


People also ask

Should I use datetime local?

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.

How to get today's date in JavaScript?

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.


2 Answers

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.

like image 184
Claudio Redi Avatar answered Sep 25 '22 16:09

Claudio Redi


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.

like image 32
Varun Natraaj Avatar answered Sep 22 '22 16:09

Varun Natraaj