Why is my date object returning back NaN values?

javascript new date() returning nan in ie
nan-undefined-nan invalid date
nan/nan/nan javascript date
date parse javascript returns nan
new date javascript
javascript date format
how to assign null value to object in javascript
javascript check null or undefined

Here is my JS fiddle:

https://jsfiddle.net/apasric4/xkzwqr1m/1/

My program is supposed to start a countdown timer that calculates the time remaining in days, hours, seconds, etc from today till the the date that the user picks in the input field.

While the program updates the HTML with the correct time remaining, the problem starts when I try to update countdown timer every second. It returns back NaN values for some reason. Why is that??

Here's my JS:

const input = document.querySelector('input')
let timeInterval;
let timeStop;


input.addEventListener('change', (e) => {
    e.preventDefault()
    timeStop = true;
    endTime = Date.parse(e.target.value)
    updateHTML(endTime)
})


function updateHTML(endTime) {
  let time = calculateTimeDiff(endTime)
  if (time.total <= 0) {
    timeStop = false;
  }
  for (let pro in time) {
    let el = document.querySelector(`.${pro}`)
    if (el) {
      el.innerHTML = time[pro];
    }
  }
  updateCounter();
}


function updateCounter () {
  if (timeStop) {
    timeInterval = setInterval(updateHTML, 1000);
  } else {
    clearInterval(timeInterval);
  }
}

//returning time remaining till date in object form 
function calculateTimeDiff(endTime) {
  let start = Date.now();
  let end = endTime;
  let t = (end-start);
  let seconds = Math.floor((t / 1000) % 60);
  let minutes = Math.floor((t / 1000 / 60) % 60);
  let hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  let days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    total: t,
    days: days,
    hours: hours,
    minutes: minutes,
    seconds: seconds
  }
}

So your code works fine but your problem is with your endTime. In your setInterval, you are calling updateHTML without the parameter endTime so that causes an error as it doesn't have a reference for the param.

You can either simply update your updateCounter function to accept this as a parameter and pass it to your setInterval function:

function updateCounter (endTime) {
  if (timeStop) {
    timeInterval=setInterval(() => updateHTML(endTime), 1000)
  } else {
    clearInterval(timeInterval)
  }
}

and then call updateCounter with the endTime at the bottom of your updateHtml function.

Or, remove endTime as a parameter from updateHtml and make it a global variable:

const input=document.querySelector('input')
let timeInterval;
let timeStop;
let endTime;


input.addEventListener('change', (e)=> {
  e.preventDefault()
  timeStop=true;
  endTime=Date.parse(e.target.value)
  updateHTML()
})


function updateHTML () {
  let time=calculateTimeDiff(endTime)
  if (time.total<=0) {
    timeStop=false
  }
  for (let pro in time) {
    let el=document.querySelector(`.${pro}`)
    if (el) {
      el.innerHTML=time[pro]
    }
  }
  updateCounter()
}


etc...

Date.parse() returns null instead of NaN · Issue #263 · abritinthebay , Unrecognisable Strings or dates containing illegal element values in the format String shall cause Date.parse to return NaN. JavaScript new Date() Returning NaN in IE or Invalid Date in Safari February 8th, 2011 - Posted by Steve Marks to Javascript / jQuery , Web Development . When it comes to programming, working with dates can be tricky.

When update goes from event - all is fine

But later you use timeInterval=setInterval(updateHTML, 1000) - and updateHTML gets executed without parameter. Use real date instead and it will work

Working example:

const input = document.querySelector('input')
let timeInterval;
let timeStop;
let savedTime;

input.addEventListener('change', (e) => {
  e.preventDefault()
  timeStop = true;
  endTime = Date.parse(e.target.value)
  updateHTML(endTime)
})

function updateHTML(endTime) {
  savedTime = endTime || savedTime;
  let time = calculateTimeDiff(savedTime)
  if (time.total <= 0) {
    timeStop = false
  }
  for (let pro in time) {
    let el = document.querySelector(`.${pro}`)
    if (el) {
      el.innerHTML = time[pro]
    }
  }
  updateCounter()
}

function updateCounter() {
  if (timeStop) {
    timeInterval = setInterval(updateHTML, 1000)
  } else {
    clearInterval(timeInterval)
  }
}

//returning time remaining till date in object form 
function calculateTimeDiff(endTime) {
  let start = Date.now()
  let end = endTime
  let t = (end - start)
  let seconds = Math.floor((t / 1000) % 60);
  let minutes = Math.floor((t / 1000 / 60) % 60);
  let hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  let days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    total: t,
    days: days,
    hours: hours,
    minutes: minutes,
    seconds: seconds
  }
}
.time {
  display: inline-block;
  border-radius: 25%;
}
<!DOCTYPE html>

<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <title></title>
  <meta name="description" content="">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="styles.css">
</head>

<body>

  <input type="date" name="endDate">
  <div class="clock">
    <div class="time"><span class="days">0</span> Days</div>
    <div class="time"><span class="hours">0</span> Hours</div>
    <div class="time"><span class="minutes">0</span> Minutes</div>
    <div class="time"><span class="seconds">0</span> Seconds</div>
  </div>


</body>

<script src="app.js"></script>

</html>

format returns "undefined NaN, 0NaN" for invalid dates · Issue #304 , kossnocorp added this to the v2.0.0 milestone on Dec 7, 2016 DATE_FORMAT​, notSetValue = null) { const value = safeParseDate(date) return value ? Make `​format` return String('Invalid Date') if date isn't valid #323. I created a new field, Cost/Quantity, and the output is coming up at NaN. I was able to see the Cost by year on a bar chart and quantity by year on a bar chart fine, but when I tried to doing Cost/Quantity on a bar chart, I am not getting anything due to NaN values.

try this....

const input=document.querySelector('input')
let timeInterval;
let timeStop;
let endTime;

input.addEventListener('change', (e)=> {
  e.preventDefault()
  timeStop=true;
  endTime=Date.parse(e.target.value)
  updateHTML()
})


function updateHTML () {
  let time=calculateTimeDiff()
  if (time.total<=0) {
    timeStop=false
  }
  for (let pro in time) {
    let el=document.querySelector(`.${pro}`)
    if (el) {
      el.innerHTML=time[pro]
    }
  }
  updateCounter()
}


function updateCounter () {
  if (timeStop) {
    timeInterval=setInterval(updateHTML(), 1000)
  } else {
    clearInterval(timeInterval)
  }
}

//returning time remaining till date in object form 
function calculateTimeDiff () {
  let start=Date.now()
  let end=endTime
  let t=(end-start)
  let seconds = Math.floor((t / 1000) % 60);
  let minutes = Math.floor((t / 1000 / 60) % 60);
  let hours = Math.floor((t / (1000 * 60 * 60)) % 24);
  let days = Math.floor(t / (1000 * 60 * 60 * 24));
  return {
    total: t,
    days: days,
    hours: hours,
    minutes: minutes,
    seconds: seconds
  }
}

Numbers and dates, This chapter introduces the concepts, objects and functions used to work with type has three symbolic values: + Infinity , - Infinity , and NaN (not-a-number). atan2(), Inverse trigonometric functions; return values in radians. NaN is a property of the global object. The initial value of NaN is Not-A-Number — the same as the value of Number.NaN. In modern browsers, NaN is a non-configurable, non-writable property. Even when this is not the case, avoid overriding it. It is rather rare to use NaN in a program.

Just add preventDefault() in function updateCounter() in your code. Hope it will work. I tried and it worked successfully.

null, The value null represents the intentional absence of any object value. const m = str.match(/[aeiou]/gi);. 3. if (m === null) {. 4. return 0;. 5. } 6. Math function is returning NaN. Well, that is exactly why i/ think this will need a function returning the value on keyup or onblur event. Does the above code work for you? Does not work for

JavaScript Number isNaN() Method, isNaN() does not convert the values to a Number, and will not return true for any value that is not of the type Number. Tip: In JavaScript, the value NaN is  Since we know what undefined and null are, and its differences, let’s say few words about NaN value. The global NaN property is a value representing Not-A-Number (source: MDN). I think the definition is clear enough. JavaScript returns this value when number we’re supposed to get isn’t a number.

JavaScript Number() Function, If the value cannot be converted to a legal number, NaN is returned. Note: If the parameter is a Date object, the Number() function returns the number of milliseconds since midnight January 1, 1970 UTC. Return Value: A Number. Returns  All numeric operations with NaN as an operand produce NaN as a result. Reason behind this is that NaN is unordered, so a numeric comparison operation involving one or two NaNs returns false. The numerical comparison operators , =, >, and >= always return false if either or both operands are NaN.( §15.20.1 )

Pandas convert string to date, Convert the date_string Series to datetime values with pd. desc. The datetime module consists of three different object Notes. nan, '', regex=True) or “​September”, pandas was able to correctly parse the string and return a formatted date. Passing and Returning Objects in Java Although Java is strictly pass by value , the precise effect differs between whether a primitive type or a reference type is passed. When we pass a primitive type to a method, it is passed by value.

Comments
  • That means you're trying to create the Date instance with a string that it cannot understand.
  • Possible duplicate of Why does Date.parse give incorrect results?
  • Also calling setInterval() again from inside the interval callback is going to cause all sorts of crazy problems.
  • timeInterval=setInterval(updateHTML, 1000) . AND function updateHTML (endTime) { . <--- SO undefined
  • setInterval(updateHTML calls updateHTML with no argument. endTime is undefined.
  • Why was it necessary to create that new variable savedTime? Why does that allow us not have to put a parameter in updateHTML when we call it every second?
  • You can do this, but you have to take it from somewhere. In your case you use date in parameter only first time when execute from event. But all timeout calls don't have an event and don't know where to take the date
  • Hey this works. But I also noticed that the countdown timer doesn't tick down by the second. It ticks down faster then that. Do you know why that is?
  • Hey I think the code didn't get formatted properly?
  • Hey why does it say maximum call stack exceeded for my code?
  • sry, try with not sending endTime as parameter to any function as its global
  • Sorry, I don't understand what you mean? Do you want me to not set endTime as global? Could you update your code so I can what you are trying to say?
  • Hey this works. But I also noticed that the countdown timer doesn't tick down by the second. It ticks down faster then that. Do you know why that is?