Click here to Skip to main content
13,796,576 members
Rate this:
 
Please Sign up or sign in to vote.
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 11-Jul-18 18:01pm
Updated 11-Jul-18 18:11pm

1 solution

Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

The correct syntax should be

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
<input id="dateinput" type="date"/>
<input type="button" onclick="calcdiff()" value="submit"/>
  Permalink  
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)

  Print Answers RSS
Top Experts
Last 24hrsThis month


Advertise | Privacy | Cookies | Terms of Service
Web04 | 2.8.181207.3 | Last Updated 11 Jul 2018
Copyright © CodeProject, 1999-2018
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100