Question

I have a Date object in JavaScript and I need to find the exact number of days, as as integer, since it occurred (between then and the current date). I know how to do this if it's within the same month, but I need this to work fine for all dates in the past. It should display 0 if it's the same physical day (after midnight) as today, 1 if it was before the most recent midnight (the previous physical day), and so on. Midnight trips a new day, not 24 hours. I tried writing this myself but it quickly became a problem as the number of days in a month changes. The Date object and the current time should already be in your local timezone, so timezones don't matter here.

Was it helpful?

Solution

Calculate the difference between begin-time and end-time.

function calc(begin, end) {
    //suppose begin, end are two Date Object to calc
    var diffmsec = end.getTime() - begin.getTime();
    var diffday = Math.floor(diffmsec / (3600*24*1000));
    var remainder = diffmsec % (3600*24*1000);
    var beginDayTime = begin.getHours()*3600*1000 + begin.getMinutes()*60*1000
                     + begin.getSeconds()*1000 + begin.getMilliseconds();
    //if [beginDayTime] + [remainder] > 1 day, [diffday]++
    if (beginDayTime + remainder > 24*3600*1000){
        diffday++;
    }
    return diffday;
}

OTHER TIPS

function parseDate(dateString) {
var mmddyy = dateString.split('/')
return new Date(mmddyy [2], mmddyy [0]-1, mmddyy [1]);}


function daydiff() {
return (parseDate($('#second').val())-parseDate($('#first').val()))/(1000*60*60*24)}

alert(Math.floor(daydiff()));
/* 2014-01-15, 11:00 */
var date = new Date(2014, 0, 15, 11, 0);
var today = new Date();
Math.abs(Math.floor((date - today) / (1000*60*60*24)))
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top