Click here to Skip to main content
15,897,187 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am experimenting with dates and i found out the values from a date type input
are strings. I want to convert the number parts of the string that is returned, to numbers.
I suppose the best way to describe what i am trying to do is by pasting in the code.

here is the relevant HTML code

<input id="dateinput" type="date"> </input>
<input type="button" onclick="calcdiff()" value="submit"> </input>


Here is my javascript code. the ctc element is where i test to see if i get the correct output.

function calcdiff() {
var datetest = document.getElementById("dateinput").value;
  var yearString = datetest.slice(0,4);
  var monthString = datetest.slice(5,7);
  var dayString = datetest.slice(8,10);
var yearNum = Number("yearString");
var monthNum = Number("monthString");
var dayNum = Number("dayString");
document.getElementById("ctc").innerHTML = yearNum;


What I have tried:

when i use typeof yearNum, i can see it is converted to a number type. However,
when i just set the innerHTML to yearNum as in the code above, it returns "NaN".
That is even though if i set the ctc element to display yearString, it displays "2018", if that is the year i choose from the date input element.

What is wrong with the code since it returns "NaN" and not the number?
Posted
Updated 11-Jul-18 17:11pm

1 solution

The correct syntax should be

JavaScript
var yearNum = Number(yearString);
  var monthNum = Number(monthString);
  var dayNum = Number(dayString);


and not Number("yearString"); because it try to convert the string "yearString" into number. Very minor changes, pass in the yearString variable.

By the way, those input elements closing tag look a little odd. it should be
HTML
<input id="dateinput" type="date"/>
<input type="button" onclick="calcdiff()" value="submit"/>
 
Share this answer
 
v3
Comments
Zigning 11-Jul-18 23:15pm    
Doh ofcourse, thanks alot!
Bryian Tan 11-Jul-18 23:21pm    
You're very welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900