Reputation: 27
I'm using javascript to take a value from HTML div field that is long date in this format: "MM/DD/YY hh:mm:ss (am/pm)". So I get the value, and what I want to do is to convert that value (which is string) into seconds, and preview it in a alert box? I tried with this code, but it shows NaN
myDivObj = document.getElementById("date").innerHTML;
var a = myDivObj.split('/');
var seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);
alert(seconds);
Any ideas?
Upvotes: 0
Views: 2058
Reputation: 9145
Right from W3Schools JavaScript Date object's reference page:
Date.parse()
Parses a date string and returns the number of milliseconds since midnight of January 1, 1970
Divide that by 1000 and you get the seconds.
var string = TextInput.value;
var seconds = (Date.parse(string)) / 1000;
alert("Seconds: "+seconds);
Upvotes: 2
Reputation: 1845
try using parseInt() to create numbers from the strings that is the output from the .split() function
myDivObj = document.getElementById("date").innerHTML;
var a = myDivObj.split('/');
var seconds = parseInt(a[0]) * 60 * 60 + parseInt(a[1]) * 60 + parseInt(a[2]);
alert(seconds);
here is a fiddle (in jQuery, I'm not much of an 'au natural' guy) http://jsfiddle.net/danieltulp/sZ9Gz/1/
Upvotes: 0