davej Posted November 29, 2012 Share Posted November 29, 2012 (edited) I'm not having much luck taking a date from HTML5 and getting it into Javascript. I have a date picker working in Chrome but how do I get that date accurately into Javascript? http://www.w3schools...me_datetime.asp http://www.w3schools...js_obj_date.asp <time id='time1' datetime="2012-11-23T01:00Z">Fri Nov 23 2012</time><form><label for="date">What date will this article be published?</label><input class="hasDatepicker" required="" id="date" name="date" type="date"><input value="Submit" type="button" id="datebtn"></form> Ok, I have something that sorta works, but I still can't read the datetime field in Javascript. I don't understand what, if anything, connects the datetime field to the displayed value, or how you generate and set the datetime field. function fndate(){var str1 = document.getElementById('date').value;var n = str1.split("-");//alert(n[0]+' '+n[1]+' '+n[2]);var d = new Date();d.setFullYear(n[0],n[1]-1,n[2]);document.getElementById('time1').innerHTML = d.toDateString();} Edited November 30, 2012 by davej Link to comment Share on other sites More sharing options...
JamesB Posted December 2, 2012 Share Posted December 2, 2012 I don't understand what, if anything, connects the datetime field to the displayed value i'm not 100% sure, but i think the displayed time is only taken from the <time> element's value, <time>here</time>,whereas the non-displayed machine-readable time is taken from 1 of 2 places, the datetime attribute, or the <time> element's value, with the datetime attribute taking priority. http://www.w3.org/TR...me-element.html To set/get the datetime attribute as a string, you can use setAttribute/getAttribute (i'm not sure if theres a better way)eg. console.log( document.getElementById('time1').getAttribute('datetime') );document.getElementById('time1').setAttribute('datetime', d.toISOString()); The toISOString() method seems to give the same date/time format as the datetime attribute.http://www.w3schools...toisostring.asp Link to comment Share on other sites More sharing options...
davej Posted December 3, 2012 Author Share Posted December 3, 2012 Interesting. Yes I noticed later that some of the date format options looked similar to the datetime attribute. I also noticed that the toLocaleString() format is very nice. Apparently I forgot to use getAttribute() and that is why I couldn't read it. Thanks. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now