views:

329

answers:

2

Hello,

i am trying to sum up or deduct dates in selected range using jquery datepicker, here is how i am doing it right now but without any luck.

function test(){
    var sundayCheck = 0;
    var saturdayCheck = 0;
    var totalDays = 0;

    sundayCheck = new Date($("#onlySunday").datepicker("getDate"));
    saturdayCheck = new Date($("#onlySaturday").datepicker("getDate"));

    totalDays = saturdayCheck.getDate() - sundayCheck.getDate();

    alert(totalDays);
}

thats a piece of code that should make calculation but what it does is just deducts days like,

24.01.10 - 06.02.10 = -18 which is totaly wrong as it should be more days its just does not consider the days and its just using first numbers of dates.

If anyone could help how to make such calculations i would appreciate the most.

+1  A: 

Are you trying to dtermine the number of days between two dates?

  totalDays = Math.ceil((saturdayCheck.getTime()-sundayCheck.getTime())/(1000*60*60*24);

First get the number of milliseconds between the two dates then divide by the number of milliseconds in a day. Using Math.ceil to round up to nearest integer.

Vincent Ramdhanie
it worked like a CHARM, but one question as for example using your code with mine and applying it to 30.01.2010 - 24.01.2010 equals = 6, but in reality i need result of 7 as 7 days passed. Do you know what i mean?
Alex
It probably depends on how you count the days. You are including the 24 in your count to get 7? If that is always going to be true then you need to +1 to the given expression.
Vincent Ramdhanie
thank you! i get the point. amazing quick response.
Alex
A: 
DAY_MSECONDS = 1000 * 60 * 60 * 24; // m-seconds in a day
var d1_ms = sundayCheck.getTime(); // date1 
var d2_ms = saturdayCheck.getTime(); // date2
var days = Math.ceil(Math.abs(d1_ms - d2_ms) / DAY_MSECONDS);

The reason you are getting -18 is because of the way javascript deals with subtracting strings. First they are evaluated to integers with whatever the default radix is, in most cases 10. So what you are doing is effectively

totalDatys = parseInt(saturdayCheck.getDate(), 10) - parseInt(sundayCheck.getDate(), 10);

which results in

totalDatys = 6 - 24 
sberry2A
is it possible to make it 7 days considered? as in reality 7 days would pass. in case of 30.01.2010 - 24.01.2010
Alex