arjuncc
arjuncc

Reputation: 3297

Date difference calculation mistake in Javascript

I use the following script to calculate date difference between two dates(with time). It works fine for most of the inputs but the problem is it returns wrong output for some inputs. What is wrong with this code

for example when I calculate date difference between

01/10/2012 11AM

and

02/10/2012 12AM

it returns 2 days as the result but its 13hrs.(as special rounding for my application it will be considered as one day) Or is there any alternative method for this. Please comment if any more details are needed.

function dstrToUTC(ds) {
             var dsarr = ds.split("/");
             var dd = parseInt(dsarr[0],10);
             var mm = parseInt(dsarr[1],10);
             var yy = parseInt(dsarr[2],10);
             var hh = parseInt(dsarr[3]); 
             return Date.UTC(yy,mm-1,dd,hh,0,0);
            }
            function datediff() {


             var roomFrom=$("#room_from").val()+"/"+$("#room_time_from").val();
             var foomTo=$("#room_to").val()+"/"+$("#room_time_to").val();
             var d1 = dstrToUTC(roomFrom);
             var d2 = dstrToUTC(foomTo);
             var oneday = 86400000;
             var dayDiff=(d2-d1) / oneday;
             var dayDiff2=Math.floor(dayDiff);


             //used to handle less than one day and, extra hours to a day
             if(dayDiff>dayDiff2)
                 dayDiff=dayDiff2+1; 

             document.getElementById("room_nodays_add").value=dayDiff;

            }

Upvotes: 0

Views: 383

Answers (1)

Nicolas Modrzyk
Nicolas Modrzyk

Reputation: 14197

This should probably not be the answer, but if you want to save time and do clean date computation in javascript, use moment.js

Upvotes: 1

Related Questions