Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
55
rated 0 times [  59] [ 4]  / answers: 1 / hits: 81595  / 15 Years ago, wed, june 24, 2009, 12:00:00

I'm writing an equipment rental application where clients are charged a fee for renting equipment based on the duration (in days) of the rental. So, basically, (daily fee * number of days) = total charge.



For instant feedback on the client side, I'm trying to use Javascript to figure out the difference in two calendar dates. I've searched around, but nothing I've found is quite what I'm looking for. Most solutions I've seen are of the form:



function dateDiff1(startDate, endDate) {
return ((endDate.getTime() - startDate.getTime()) / 1000*60*60*24);
}


My problem is that equipment can be checked out and returned at any time of day during those two dates with no additional charge. The above code is calculating the number of 24 hour periods between the two dates, when I'm really interested in the number of calendar days.



For example, if someone checked out equipment at 6am on July 6th and returned it at 10pm on July 7th, the above code would calculate that more than one 24 hour period had passed, and would return 2. The desired result is 1, since only one calendar date has elapsed (i.e. the 6th to the 7th).



The closest solution I've found is this function:



function dateDiff2(startDate, endDate) {
return endDate.getDate() - startDate.getDate();
}


which does exactly what I want, as long as the two dates are within the same month. However, since getDate() only returns the day of month (i.e. 1-31), it doesn't work when the dates span multiple months (e.g. July 31 to August 1 is 1 day, but the above calcuates 1 - 31, or -29).



On the backend, in PHP, I'm using gregoriantojd(), which seems to work just fine (see this post for an example). I just can't find an equivalent solution in Javascript.



Anyone have any ideas?


More From » date

 Answers
65

If you want whole days for your student camera rental example ...



function daysBetween(first, second) {

// Copy date parts of the timestamps, discarding the time parts.
var one = new Date(first.getFullYear(), first.getMonth(), first.getDate());
var two = new Date(second.getFullYear(), second.getMonth(), second.getDate());

// Do the math.
var millisecondsPerDay = 1000 * 60 * 60 * 24;
var millisBetween = two.getTime() - one.getTime();
var days = millisBetween / millisecondsPerDay;

// Round down.
return Math.floor(days);
}

[#99252] Friday, June 19, 2009, 15 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
margaritakristinak

Total Points: 502
Total Questions: 127
Total Answers: 98

Location: England
Member since Mon, May 17, 2021
3 Years ago
;