38

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>
}
4
  • 2
    What format is the "time stamp", ISO8601? And the non–timestamp string looks like…?
    – RobG
    May 27, 2013 at 6:16
  • 1
    var diff=Math.abs(date1-date2);
    – elclanrs
    May 27, 2013 at 6:17
  • @elclanrs—I think maybe there's some parsing first.
    – RobG
    May 27, 2013 at 6:19
  • @RobG this is the format I have in the List Mon May 27 11:46:15 IST 2013. I need to convert this into a timestamp, get the difference between this and the current time in minutes.
    – swateek
    May 27, 2013 at 6:41

5 Answers 5

71

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 ');
}
5
  • what if I needed the current time in date1. Will var date1=new Date.getTime(); do the trick?
    – swateek
    May 27, 2013 at 6: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, 2013 at 6:49
  • var date = new Date(Date.parse(YourstringDate.replace(/-/g, " ")));
    – Anuj
    May 27, 2013 at 6: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, 2013 at 7: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, 2013 at 7:22
31

Based on the approved answer:

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

    return daysDifference;
}
1
  • 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 0s 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, 2018 at 10:10
4

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)

1
  • If using NodeJS, here is what will be helpful RequireJS (stackoverflow.com/questions/46436943/…) const {performance} = require('perf_hooks'); const t0 = performance.now(); ES6 Module import { performance } from 'perf_hooks'; const t0 = performance.now(); Jul 27, 2021 at 2:12
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.

-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(),
});
3
  • 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.
    – Community Bot
    Apr 3, 2022 at 2: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: jsfiddle.net/uLp9a5md
    – Stephan
    May 21, 2022 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, 2022 at 0:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.