17

I have a date object created from vars saved in a database.

var prevTime = Date(year,month,day,hour,minute);

I want to calculate the difference between this and the current time.

var thisTime = Date();

I am doing this:

prevTime.getTime() - thisTime.getTime();

It gives me a negative number that is very large. I divide by 1000 to get seconds and then divide by 3600 to get hours. I need an elapsed time in hours. I end up with a number that is like -756.00. If the current time is larger than the previous time, why is the number negative? What am I doing wrong?

Thanks,

Scott

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
llihttocs
  • 2,001
  • 3
  • 14
  • 10
  • 6
    Because you're subtracting the current time from the previous time. You have to subtract the prev. time from the current time: `thisTime - prevTime`. – Šime Vidas Jul 09 '11 at 18:23
  • 1
    possible duplicate of [How to subtract date/time in javascript?](http://stackoverflow.com/questions/4944750/how-to-subtract-date-time-in-javascript) – Felix Kling Jul 09 '11 at 18:31

4 Answers4

23

The current time is larger than the previous time so subtracting a larger number from a smaller number gives you a negative number. Reverse the order if you want the positive difference in times. Is there more to the question than that?

Demonstration here: http://jsfiddle.net/jfriend00/NYSsp/

var prevTime = new Date(2011,1,1,0,0);  // Feb 1, 2011
var thisTime = new Date();              // now
var diff = thisTime.getTime() - prevTime.getTime();   // now - Feb 1
alert(diff / (1000*60*60*24));     // positive number of days
donohoe
  • 13,867
  • 4
  • 37
  • 59
jfriend00
  • 683,504
  • 96
  • 985
  • 979
  • Yes. I apologize. I was nervous when I typed in the question. I am doing thisTime.getTime() - prevTime.getTime(); When I debug or output to the console, I see that the current date is larger than the previous one. I still seem to get the negative number that is much too large. Any thoughts? – llihttocs Jul 09 '11 at 18:40
  • Look at my fiddle for a working example. This type of code needs to be: var prevTime = new Date(year,month,day,hour,minute); with the "new" in it if you want to be able to call the getTime() methods. – jfriend00 Jul 09 '11 at 18:44
  • After more debugging, the problem seems to be coming from how I create the previous date object. Here is a code snippet: – llihttocs Jul 09 '11 at 18:56
  • Did it again. Damnit! console.log('Yr: '+tcdYear+', Mn: '+tcdMon+', Dy: '+tcdDay+', Hr: '+tcdHour+', Mn: '+tcdMin); var tcdTime = new Date(tcdYear, tcdMon, tcdDay, tcdHour, tcdMin); console.log('tcdTime: '+tcdTime.getTime()+', '+tcdTime); var currentTime = new Date(); console.log('currentTime: '+currentTime.getTime()+', '+currentTime); – llihttocs Jul 09 '11 at 18:58
  • Output from the console:1741Yr: 2011, Mn: 7, Dy: 9, Hr: 12, Mn: 52 /C:/Users/shill/Documents/bt/bt.js:1743tcdTime: 1312915920000, Tue Aug 09 2011 12:52:00 GMT-0600 (Mountain Daylight Time) /C:/Users/shill/Documents/bt/bt.js:1745currentTime: 1310237633608, Sat Jul 09 2011 12:53:53 GMT-0600 (Mountain Daylight Time) Why does the first date show Tue instead of Sat? – llihttocs Jul 09 '11 at 18:58
  • I can't follow your code in comments here. I'd suggest you put your code sample in http://jsfiddle.net and then post a link here. Free sign-up and then you can prototype/test/share easily and I can see/debug exact the same code sample that you have. Much better way to share. – jfriend00 Jul 09 '11 at 19:05
  • Du... Found the problem. I was forgetting to decrement the month before I created the previous date. I was getting a date one month in the future. Sorry about the messy comments. The jsfiddle looks cool. I will remember that for next time. – llihttocs Jul 09 '11 at 19:18
  • The only problem that I have found in this logic is when you hit a time change (daylight savings time). If you do this method with the dates of 3/8/2016 and 3/24/2016, you will get 15.958333333333334 instead of the expected value of 16 as you loose an hour within this time frame. I haven't tested it yet, but I think if you round this value the logic will then work as you have to deal with both cases (gaining and loosing an hour). – dmoore1181 Mar 08 '16 at 18:34
  • Just tested it and the following will work for the time change issue: `Math.round(((departure.getTime() - arrival.getTime())/1000)/86400)` – dmoore1181 Mar 08 '16 at 19:07
1

First one must be smaller that you get negative. Your first date is in the past.

Here is an example:

var a = new Date(2011,7,5,2,1,1) - new Date(2011,7,5,1,1,1);
alert(a); // 3600000 which is millisecond for 1 hour. Divide by this to get hours.
Aliostad
  • 80,612
  • 21
  • 160
  • 208
0

IF you want Date and Time in Dynamic Run on web Page and also the Login time i.e the clock starts from the start of java function scipt and also gives how many hours,minutes and seconds you are online in the Application or a Particular web Page For this just call the javascript function in the html body load.

<script type="text/javascript">
var second;
var first = new Date;
function date_time() {
    var id = 'Label1'
    date = new Date;
    second = date.getTime();
    year = date.getFullYear();
    month = date.getMonth();
    months = new Array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
    d = date.getDate();
    day = date.getDay();
    days = new Array('Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday');
    h = date.getHours();
    if (h < 10) {
        h = "0" + h;
    }
    m = date.getMinutes();
    if (m < 10) {
        m = "0" + m;
        //min = min+1;
    }
    s = date.getSeconds();
    if (s < 10) {
        s = "0" + s;
        //sec = sec+1;
    }
    var timeDiff = second - first.getTime();
    var hours = Math.floor(timeDiff / (1000 * 60 * 60));

    timeDiff -= hours * (1000 * 60 * 60);



    var mins = Math.floor(timeDiff / (1000 * 60));

    timeDiff -= mins * (1000 * 60);

    var secs = Math.floor(timeDiff / 1000)
    timeDiff -= secs * 1000;

    result = 'LoginTime(HH:MM:SS) ' + hours + ':' + mins + ':' + secs + ' ' + days[day] + ' ' + months[month] + ' ' + d + ' ' + year + ' Clock(24hr): ' + h + ':' + m + ':' + s;
    document.getElementById(id).innerHTML = result;
    setTimeout('date_time("' + id + '");', '1000');
    return true;
}

By Santosh Kumar Murarkar

-1

Check this:

var first = new Date();
for(i = 0; i<10000; i++) // Some loop to make a little time pass
{
    i = i;
}
var second = new Date();

second.getTime() - first.getTime();
Saeed Neamati
  • 35,341
  • 41
  • 136
  • 188