1

I am working on a small webapp for calculating the count of days.

What i've figured out is:

function cost() {

var oneDay = 24*60*60*1000; //hours*minutes*seconds*milliseconds
var firstDate = new Date(2008,01,12); //Would like to input it myself
var secondDate = new Date(2008,01,22); //Would like to input it myself

var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay));

var priceInDays = diffDays * 250;

alert(priceInDays);

}

What I would like instead is to set the dates dynamically. I am using the Chrome date picker what will return the date as: 2017-03-30. I've tried something like this:

var firstDate =  document.getElementById('dateRent').value;
var secondDate = document.getElementById('dateEnd').value; 

But that didn't work out. So now, the dates are set the hard coded way. It will give me 10 * 250 = 2500 in the alert box.

I've created a jsfiddle (one problem, it doesn't handle my function, can't find the problem. https://jsfiddle.net/w93c571x/3/

Giesburts
  • 6,879
  • 15
  • 48
  • 85

1 Answers1

1

You're very close. Try this instead:

var firstDate =  new Date(document.getElementById('dateRent').value);
var secondDate = new Date(document.getElementById('dateEnd').value);

Also to fix your fiddle, add an id attribute to the calculate button, and call the cost() function in an event listener, like so:

HTML

<a href="#" id="calculate">Calculate!</a>

JS

document.getElementById('calculate').addEventListener('click', cost);

Here's a working fiddle.

musicnothing
  • 3,977
  • 24
  • 43
  • Tried this option already before, I guess I made a mistake that moment. Thanks! :) – Giesburts Mar 30 '17 at 18:53
  • Be careful of this method. If the built-in parser correctly parses "2017-03-30" (and some do not) then it will be treated as UTC. That doesn't matter in this case as you just want the difference between two dates in days, but if you write the date to output, it will be adjusted for the host timezone offset and hence may look like a different date, see [*Why does Date.parse give incorrect results?*](http://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Mar 31 '17 at 05:09
  • 1
    @RobG That is a very good point. For this purpose (difference between dates) it should be fine, but in some timezones parsing the current date will tell you it's yesterday – musicnothing Mar 31 '17 at 15:59