Sometimes beginners programmers face this general problem while creating dynemic web applications. When we try to fetch JavaScript Date value in HTML DOM<input type="date">it doesn't set the date.
Hello Programmers! This JavaScript tutorial will elaborate "How to get JavaScript Date in input type='date' element?".

Sometimes beginners programmers face this general problem while creating dynamic web applications. When we try to fetch JavaScript Date value in HTML DOM <input type="date"> it doesn't set the date.

Set a date value for date field:

document.getElementByID("demo_date").value = "2019-08-20";
Try Yourself

Above example return the result




In the above example a date string is set to HTML input type=”date” value very easily but when working with JavaScript date constructor ‘new Date()’, it create problems. We have various solutions for this problem. You can try this one :

Set a date value for date field:

today = year.toString().padStart(4, '0')+'-'+month.toString().padStart(2, '0')+'-'+day.toString().padStart(2, '0');
Try Yourself

Another solution using 'toISOString()' method.
In below given example we have used JavaScript toISOString() method with a little trick. toISOString() method returns the International Standard time. Local-time may be different from other time standard. To rectify this problem we have find the time difference between UTC and local-time using 'getTimezoneOffset()' method, converted into milliseconds and added to the local-time. After that we have converted the time to ISOString() and extracted the date using substr(0, 10) method.

Set a date value for date field:

var d = new Date().getTimezoneOffset();
var date = new Date(new Date().getTime() - d * 60 * 1000);
document.querySelector('[name=date]').value=date.toISOString().substr(0, 10); 

progrramers-logo

progrramers

Hello friends! Progrramers is a tutorial site of w3 programming. If you like this tutorial site please encourages us by sharing this site links with your friends and nears & dears who want to learn web development and give us like on our Facebook page. If have any question please type in to comment box or send us message on social media sites via below given social links. Thank you, have a nice learning.

Post A Comment:

1 comments:

  1. Wow! Such an amazing and helpful post this is. I really really love it. It's so good and so awesome. I am just amazed. I hope that you continue to do your work like this in the future also.
    artificial intelligence ai and deep learning in Guwahati

    ReplyDelete