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/

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

Tried this option already before, I guess I made a mistake that moment. Thanks! :)
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?
@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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.