Calculating difference between two dates using JS

Y

Yotam

Hi,
I need some help with JS. I will be grateful, if you can help me out.
I have two date fields (check in, check out) and "number of days"
field.
I want the script to calculate automatically the difference.
For example: I have defaults dates, and I want the script to put the
difference in "number of days" field. And if the user will change the
date, the number of days will change automatically.


Thanks,
Yotam
 
R

RobG

Yotam said:
Hi,
I need some help with JS. I will be grateful, if you can help me out.
I have two date fields (check in, check out) and "number of days"
field.
I want the script to calculate automatically the difference.
For example: I have defaults dates, and I want the script to put the
difference in "number of days" field. And if the user will change the
date, the number of days will change automatically.

Everything you ever wanted to know about date arithmetic (and then
some):

<URL: http://www.merlyn.demon.co.uk/js-dates.htm >
 
J

jezaustin

The date arithmetic problem is solved, I take it. All you need to do is
attach the function to eg onchange events for your text fields.

eg. something like
<input name="checkin" onchange="doArithmetic()" />
<input name="checkout" onchange="doArithmetic()" />

Unfortunately, iirc onchange waits until input focus is moved away from
the text field before triggering, so in my applications I've ended up
using the onkeypress event. (I experimented with a few keyboard events,
this one works best across the browsers.) This calls the function
before updating the text element's value, so I also enclose the
function in a setTimeout to make sure it sees the new value.
elem.onkeypress = function() { setTimeout( 'somefunction(someargs)', 50
); };
This waits 50ms before calling the function, by which time elem.value
is at the newly entered value.

HTH
 
D

Dr J R Stockton

Fri said:
Hi,
Thanks for your reaply.
All the examples is this site
(<URL:http://www.merlyn.demon.co.uk/js-dates.htm>) are with buttons
(the user have to press a button for the function to calculate).

I'm looking for a function that does that automatically.


Here is a minimal demo of one way to do it, though setInterval is
sub-elegant for the purpose.

<input name=X> - <input name=Y> = <input name=Z readonly>
<script>
setInterval(
"Z.value=Math.round((new Date(X.value)-new Date(Y.value))/864e5)",
1000)
</script>

To be reasonably sure of further interest, read the FAQ and format your
responses correctly.

It's a good idea to read the newsgroup FAQ. See below.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top