Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript DateDiff

I am having a problem with the DateDiff function. I am trying to figure out the Difference between two dates/times. I have read this posting (What's the best way to calculate date difference in Javascript) and I also looked at this tutorial (http://www.javascriptkit.com/javatutors/datedifference.shtml) but I can't seem to get it.

Here is what I tried to get to work with no success. Could someone please tell me what I am doing and how I can simplify this. Seems a little over coded...?

//Set the two dates
var currentTime = new Date();
var month = currentTime.getMonth() + 1;
var day = currentTime.getDate();
var year = currentTime.getFullYear();
var currDate = month + "/" + day + "/" + year;
var iniremDate = "8/10/2012";

//Show the dates subtracted
document.write('DateDiff is: ' + currDate - iniremDate);

//Try this function...
function DateDiff(date1, date2) {
    return date1.getTime() - date2.getTime();
}

//Print the results of DateDiff
document.write (DateDiff(iniremDate, currDate);
like image 251
Frank G. Avatar asked Aug 17 '12 10:08

Frank G.


1 Answers

Okay for those who would like a working example here is a simple DateDiff ex that tells date diff by day in a negative value (date passed already) or positive (date is coming).

EDIT: I updated this script so it will do the leg work for you and convert the results in to in this case a -10 which means the date has passed. Input your own dates for currDate and iniPastedDate and you should be good to go!!

//Set the two dates
var currentTime   = new Date()
var currDate      = currentTime.getMonth() + 1 + "/" + currentTime.getDate() + "/" + currentTime.getFullYear() //Todays Date - implement your own date here.
var iniPastedDate = "8/7/2012" //PassedDate - Implement your own date here.

//currDate = 8/17/12 and iniPastedDate = 8/7/12

function DateDiff(date1, date2) {
    var datediff = date1.getTime() - date2.getTime(); //store the getTime diff - or +
    return (datediff / (24*60*60*1000)); //Convert values to -/+ days and return value      
}

//Write out the returning value should be using this example equal -10 which means 
//it has passed by ten days. If its positive the date is coming +10.    
document.write (DateDiff(new Date(iniPastedDate),new Date(currDate))); //Print the results...
like image 149
Frank G. Avatar answered Oct 02 '22 00:10

Frank G.