40

I have to calculate the difference between 2 timestamps. Also can you please help me with conversion of a string into timestamp. Using plain javascript only. NO JQUERY.

Here's my function:

function clearInactiveSessions()
{
    alert("ok");
    <c:if test="${not empty pageScope.sessionView.sessionInfo}">
        var currentTime = new Date().getTime();
        alert("curr:"+currentTime);
        var difference=new Date();
        <c:forEach items="${pageScope.sessionView.sessionInfo}" var="inactiveSession">
            var lastAccessTime = ${inactiveSession.lastUpdate};
            difference.setTime(Maths.abs(currentTime.getTime()-lastAccessTime.getTime()));
            var timediff=diff.getTime();
            alert("timediff:"+timediff);
            var mins=Maths.floor(timediff/(1000*60*60*24*60));
            alert("mins:"+mins);
            if(mins<45)
                clearSession(${item.sessionID});
        </c:forEach>
    </c:if>
}
swateek
  • 6,735
  • 8
  • 34
  • 48

5 Answers5

72

i am posting my own example try implement this in your code

function timeDifference(date1,date2) {
    var difference = date1.getTime() - date2.getTime();

    var daysDifference = Math.floor(difference/1000/60/60/24);
    difference -= daysDifference*1000*60*60*24

    var hoursDifference = Math.floor(difference/1000/60/60);
    difference -= hoursDifference*1000*60*60

    var minutesDifference = Math.floor(difference/1000/60);
    difference -= minutesDifference*1000*60

    var secondsDifference = Math.floor(difference/1000);

    console.log('difference = ' + 
      daysDifference + ' day/s ' + 
      hoursDifference + ' hour/s ' + 
      minutesDifference + ' minute/s ' + 
      secondsDifference + ' second/s ');
}
gdbdable
  • 4,445
  • 3
  • 30
  • 46
Anuj
  • 1,496
  • 1
  • 18
  • 28
  • what if I needed the current time in date1. Will var date1=new Date.getTime(); do the trick? – swateek May 27 '13 at 06:38
  • if I have a string like "Mon May 27 11:46:15 IST 2013" how can i convert it into timestamp and calculate difference in minutes between this and the current time..pleasE? – swateek May 27 '13 at 06:49
  • var date = new Date(Date.parse(YourstringDate.replace(/-/g, " "))); – Anuj May 27 '13 at 06:53
  • When I use this: var temp_date = "Mon May 27 11:46:15 IST 2013"; var lastAccessTime = new Date(Date.parse(temp_date.replace(/-/g, " "))).getTime(); alert(lastAccessTime); -> gives me NaN. Why? – swateek May 27 '13 at 07:09
  • format temp_date to some Date format like dd/MM/yyy or dd/MMM/yyyy and then try the same code – Anuj May 27 '13 at 07:22
32

Based on the approved answer:

function(timestamp1, timestamp2) {
    var difference = timestamp1 - timestamp2;
    var daysDifference = Math.floor(difference/1000/60/60/24);

    return daysDifference;
}
Combine
  • 3,894
  • 2
  • 27
  • 30
  • 2
    dunno why this was downvoted. if you two dates are in the ACTUAL timestamp format : E.G. `1503964800000` (which is definitely simpler to work with than crap containing maybe `/` maybe `-` and an uncertain amount of `0`s before the digits and with the three members coming sometimes with a certain arrangement sometimes another.) then is is the better, simpler answer. – tatsu Mar 15 '18 at 10:10
5

A better alternative would be using window.performance API.

const startTime = window.performance.now()
setTimeout(()=>{
 const endTime = window.performance.now()
 console.log("Time Elapsed : ",endTime-startTime) // logs ~2000 milliseconds
}, 2000)

Update for node.js since window.performance is not available in nodejs.


const {performance} = require('perf_hooks');
const startTime = performance.now();

    setTimeout(()=>{
     const endTime = performance.now();
     console.log("Time Elapsed : ",endTime-startTime) // logs ~2000 milliseconds
    }, 2000)

AnandShiva
  • 906
  • 11
  • 22
  • 1
    If using NodeJS, here is what will be helpful RequireJS (https://stackoverflow.com/questions/46436943/referenceerror-performance-is-not-defined-when-using-performance-now#50179733) ```const {performance} = require('perf_hooks'); const t0 = performance.now();``` ES6 Module ```import { performance } from 'perf_hooks'; const t0 = performance.now();``` – wakqasahmed Jul 27 '21 at 02:12
  • thanks @wakqasahmed. Updated the answer with your inputs. – AnandShiva Apr 12 '23 at 05:53
0

If your string is Mon May 27 11:46:15 IST 2013, you can convert it to a date object by parsing the bits (assuming 3 letter English names for months, adjust as required):

// Convert string like Mon May 27 11:46:15 IST 2013 to date object 
function stringToDate(s) {
  s = s.split(/[\s:]+/);
  var months = {'jan':0, 'feb':1, 'mar':2, 'apr':3, 'may':4, 'jun':5, 
                'jul':6, 'aug':7, 'sep':8, 'oct':9, 'nov':10, 'dec':11};
  return new Date(s[7], months[s[1].toLowerCase()], s[2], s[3], s[4], s[5]);
}

alert(stringToDate('Mon May 27 11:46:15 IST 2013'));

Note that if you are using date strings in the same timezone, you can ignore the timezone for the sake of difference calculations. If they are in different timezones (including differences in daylight saving time), then you must take account of those differences.

RobG
  • 142,382
  • 31
  • 172
  • 209
-1

A simple deal to get the time difference.

var initialTime = new Date();
var finalTime = new Date();

console.log({
    days: finalTime.getDay() - initialTime.getDay(),
    hours: finalTime.getHours() - initialTime.getHours(),
    minutes: finalTime.getMinutes() - initialTime.getMinutes(),
    seconds: finalTime.getSeconds() - initialTime.getSeconds(),
    milliseconds: finalTime.getMilliseconds() - initialTime.getMilliseconds(),
});
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Apr 03 '22 at 02:17
  • If `initialTime = '2022-01-01 01:00:00'` and `finalTime = '2022-01-08 02:00:00'`, the snippet outputs 1 hour while there are 25 hours. See here: https://jsfiddle.net/uLp9a5md/ – Stephan May 21 '22 at 21:11
  • This approach also has a bug in that any `finalTime` that is in the following day will have a day count of >0 regardless of whether the finalTime is 24 hours ahead of the `initial time`. I submitted an edit for this before realising this, and don't know how to remove my edit request, as the approach outlined in this answer is structually flawed. – Sean May 25 '22 at 00:35