When we need to calculate the difference between two dates using javascript we need to convert the string to date and here is the code to do this

dateCustom= new Date('2013/05/28 07:40 PM');
dateCurrent = new Date();
var totalDiff = dateCurrent.getTime() - dateCustom.getTime();
var objDiff = new Object();
objDiff.days = Math.floor(totalDiff/1000/60/60/24);
totalDiff -= objDiff.days*1000*60*60*24;
objDiff.hours = Math.floor(totalDiff/1000/60/60);
totalDiff -= objDiff.hours*1000*60*60;
objDiff.minutes = Math.floor(totalDiff/1000/60);
totalDiff -= objDiff.minutes*1000*60;
objDiff.seconds = Math.floor(totalDiff/1000);
alert(objDiff.days + " days " +objDiff.hours 
+ " hours " +objDiff.minutes + " minutes " +objDiff.seconds + " seconds ");

And to find the difference in hours

dateCustom= new Date('2013/05/28 07:40 PM');
dateCurrent = new Date();
var totalDiff = dateCurrent.getTime() - dateCustom.getTime();
var objDiff = new Object();
oDiff.hours= Math.floor(nTotalDiff/1000/60/60);
alert(objDiff.hours + " hours);

And to find the difference in minutes

dateCustom= new Date('2013/05/28 07:40 PM');
dateCurrent = new Date();
var totalDiff = dateCurrent.getTime() - dateCustom.getTime();
var objDiff = new Object();
oDiff.minutes= Math.floor(nTotalDiff/1000/60);
alert(objDiff.minutes + " minutes);

Leave a Reply

Your email address will not be published.