16

I am currently trying to take the value from an HTML input (below)

<input type="date" id="dateInput" />

and put it into a javascript variable so I can use it for other things. I currently am using the code below.

    var input = document.getElementById("dateInput").value;
    var dateEntered = new Date(input);

But when I test those variables, it tells me that Input is "" and dateEntered is "Invalid Date".

I've tried the .valueAsDate instead of just .value as well. When I test those out, it tells me that Input is null and dateEntered is "Wed Dec 31 1969 19:00:00 GMT-0500 (Eastern Standard Time)" even though I entered today's date.

How would I fix this so that the javascript variables actually reflect the date I enter? I am using Google Chrome as my browser.

EDIT and UPDATE For those who wanted my whole code, indentation is a little off sorry:

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <meta name="viewport" content="width=device-width,initial-scale=1.0">
   <title>Calculate Time</title>
   <link rel="stylesheet" href="styles.css" />  
   <script src="modernizr.custom.05819.js"></script>
</head>
<body>
   <header>
      <h1> Calculate Time </h1>
   </header>
   <article align="center">
      <div id="cities">
          // My navigation links here (REMOVED)
      </div>
  <div id="caption">
     Calculate the time elapsed since a date entered.
  </div>
   <div class="box">
       <article>
           <form>
               <fieldset>
                   <label for="dateEntered">
                       Enter a Date
                   </label>
                   <input type="date" id="dateInput" />
               </fieldset>
               <fieldset class="button">
                   <button type="button" id="determineTime">Find Time</button>
               </fieldset>
               <fieldset>
                   <p>Time Elapsed is:</p>
                   <p id="time"></p>
               </fieldset>
           </form>
       </article>
   </div>
   <div id="map"></div>
  </article>
    <script>
        var input;
        var dateEntered;

        document.getElementById("dateInput").addEventListener("change", function () {
        input = this.value;
        dateEntered = new Date(input);
        });

    /* find and display time elapse */
    function lookUpTime() {
        // More code will go here later.
    }

    // add event listener to Find time button and clear form
    function createEventListener() {
        var submitButton = document.getElementById("determineTime");
        if (submitButton.addEventListener) {
            submitButton.addEventListener("click", lookUpTime, false);
        } else if (submitButton.attachEvent) {
            submitButton.attachEvent("onclick", lookUpTime);
        }
        document.getElementById("dateInput").value = "";
        // clear last starting value on reload
        document.getElementById("time").innerHTML = "";
        // clear previous results on reload
    }

    if (window.addEventListener) {
        window.addEventListener("load", createEventListener, false);
    } else if (window.attachEvent) {
        window.attachEvent("onload", createEventListener);
    }
</script>
<script src="script.js"></script>
</body>
</html>
Arnatuile
  • 185
  • 1
  • 1
  • 5
  • can you post the entire JS code? – Lucky Chingi Nov 11 '15 at 20:48
  • At which point do you set those variables? If you set them at page load, then obviously the value will be empty. Show a complete example please. – JJJ Nov 11 '15 at 20:50
  • Possible duplicate of [Converting string to date in js](http://stackoverflow.com/questions/5619202/converting-string-to-date-in-js) – CY5 Nov 11 '15 at 20:54
  • Possible duplicate of [How do you parse a date from an HTML5 date input?](https://stackoverflow.com/questions/16825363/how-do-you-parse-a-date-from-an-html5-date-input) – Liam Sep 10 '18 at 10:48

2 Answers2

24
document.getElementById("dateInput").addEventListener("change", function() {
    var input = this.value;
    var dateEntered = new Date(input);
    console.log(input); //e.g. 2015-11-13
    console.log(dateEntered); //e.g. Fri Nov 13 2015 00:00:00 GMT+0000 (GMT Standard Time)
});

Basically you need to listen for the change of your date input, currently you were trying to get the value on load, when the picker has no date in it hence you get 'Invalid Date'

luanped
  • 3,178
  • 2
  • 26
  • 40
  • well your answer is correct till user enter Date in ISO format: YYYY-MM-DD or YYYY-MM-DDTHH:MM:SS but the OP haven't specifed the format – CY5 Nov 11 '15 at 21:00
  • 1
    I assumed the date will be modified from the input type 'date', and from my understanding there is no way to provide it in other formats other than yyyy-mm-dd ?? – luanped Nov 11 '15 at 21:03
  • 1
    @CY5 `` is always in that format. – JJJ Nov 11 '15 at 21:03
  • @Juhana well input type date is what Chrome support which has good datepicker all that stuff.. but in firefox and IE 10 its not check this out https://jsfiddle.net/73ebffud/1/ – CY5 Nov 11 '15 at 21:16
  • Oh thank you! The first console.log(input) works great. But my problem now is that the 2nd console.log(dateEntered) is showing one day earlier than it is supposed to. When I enter 11/11/2015 it says Tue Nov 10 2015.... – Arnatuile Nov 11 '15 at 21:22
  • @Arnatuile input type date is a concept Google came up with and is in their whatwg specifications (not official) and is only partially supported by Chrome by Chris Love http://stackoverflow.com/questions/22983013/how-to-get-html-5-input-type-date-working-in-firefox-and-or-ie-10#answer-22983753 so your date format will not work in FireFox and IE 10 whatever user enters it will take that format check here example https://jsfiddle.net/73ebffud/2/ you get that bug becoz you might be doing it in IE10 or firefox – CY5 Nov 11 '15 at 21:28
  • Like i stated in my post above, I am using Google Chrome, not IE or firefox. – Arnatuile Nov 11 '15 at 21:34
  • @Arnatuile Which version of Chrome are you using? That's a very strange behaviour which I can't seem to reproduce in Chrome 46 – luanped Nov 11 '15 at 21:39
  • I have Version 46.0.2490.80 of Chrome. – Arnatuile Nov 11 '15 at 21:41
  • 1
    @Arnatuile your format of Date is wrong 11/11/2015 chrome accept the date YYYY-MM-DD – CY5 Nov 11 '15 at 21:42
  • Well when you add an input box with type="date" it auto shows IN THE BOX mm/dd/yyyy. I did not format anything. You can then select a date from a calendar or type it. Then it goes into the variable input as "2015-11-11" just fine. The problem is when you go from the variable "input" and try to make it a date variable "dateEntered". It subtracts a day for some reason. Is there a way to just add one day to it? So in a way it corrects it. – Arnatuile Nov 11 '15 at 21:50
  • @Arnatuile I copied part of your code from above and added 2 console logs: https://jsfiddle.net/fduho9sb/ on my machine the output seems consistent between the 2 variables, could you have a look at this ? – luanped Nov 11 '15 at 21:50
  • @luanped For me those two are different. I tried it in Edge too. So maybe it is just my computer? it still says the second console.log is a day short. – Arnatuile Nov 11 '15 at 21:55
  • @Arnatuile its not your browser Date() take time from your internal system not from any server or anything else – CY5 Nov 11 '15 at 22:05
  • Maybe I will just take my input variable and take out the different parts of it. The whole goal of this assignment (its for a class) is to take a date in from a user and calculate how much time has passed in years, months, and days. I am supposed to use .getFullYear() .getMonth() and that jazz. But this is not going well for me. – Arnatuile Nov 11 '15 at 22:11
  • You could have a look at http://momentjs.com/ - might be of help for what you are trying to achieve – luanped Nov 11 '15 at 22:13
  • FYI: These events will fire with a blank value if the keyboard is used to select a date that is not valid. ie. Feb 30. https://stackoverflow.com/questions/48564568/html5-input-type-date-input-event-incorrectly-fires-with-empty-value/48564701#48564701 – Olmstov Feb 01 '18 at 14:25
-7

Make sure your script is executing after the DOM has fully loaded. To do this you can put your JS code in a function and call the function once the DOM has loaded, or just put your JS code at the end of your page, right before </body>.

rby
  • 754
  • 6
  • 10