Jump to content

Javascript Date() and HTML5 datetime ?


davej

Recommended Posts

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 by davej
Link to comment
Share on other sites

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

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

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 account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...