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
Try Yourself
Above example return the result
In the above example a date string is set to HTML
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.
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";
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');
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);
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.
ReplyDeleteartificial intelligence ai and deep learning in Guwahati