Click here to Skip to main content
15,886,873 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am trying to get days difference between two dates using Javascript.
using getTime() function, getting milliseconds and this is my code.
JavaScript
function daysdifference(date1, date2) {
            // The number of milliseconds in one day
            var ONEDAY = 1000 * 60 * 60 * 24;
            // Convert both dates to milliseconds
            var date1_ms = date1.getTime();
            var date2_ms = date2.getTime();
            // Calculate the difference in milliseconds
            var difference_ms = Math.abs(date1_ms - date2_ms);

            // Convert back to days and return
            return Math.round(difference_ms/ONEDAY);
        }


Not getting accurate result. This method seems not working. am i doing some mistake?
Is there any other better approach to have days difference?
Thanks
Posted
Comments
What is the problem? Can you explain examples?
Schatak 26-Aug-14 8:13am    
e.g. if i pass 2014-08-01 as date1 and 2014-08-26 as date2 its not working but if i do it like
date1 = new Date(2014, 0, 1); // any custom date
date2 = new Date() //Today date

then its working. my req is to pass custom date as user input

Please check once this way,

C#
var startDate = Date.parse("2014-08-01");
            var endDate = Date.parse("2014-08-26");
            var timeDiff = endDate - startDate;
            daysDiff = Math.floor(timeDiff / (1000 * 60 * 60 * 24));
 
Share this answer
 
Comments
Schatak 27-Aug-14 1:44am    
will it work with any date format?
Sanchayeeta 27-Aug-14 3:32am    
This will take Date as yyyy-MM-dd ,yyyy/MM/dd format, yyyy,MM/dd format.
Schatak 27-Aug-14 4:11am    
Yeah i see that. my req. was to pass any date format, any ways i made separate function to convert date in this format and then find the days difference with ur logic.
Thanks
JavaScript
var date1 = new Date("7/11/2010");
var date2 = new Date("12/12/2010");
var timeDiff = Math.abs(date2.getTime() - date1.getTime());
var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); 
alert(diffDays)​;
 
Share this answer
 
Comments
Schatak 27-Aug-14 1:43am    
not working and reason is you are passing wrong parameter in Date function
Thanks anyways :)
 
Share this answer
 
You could use momentjs, it calculates differencies and much more, if you're dealing with dates it can be helpful :)
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900