Calculate difference between 2 timestamps using ja

2019-02-04 17:43发布

问题:

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>
}

回答1:

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);

     document.WRITE('difference = ' + daysDifference + ' day/s ' + hoursDifference + ' hour/s ' + minutesDifference + ' minute/s ' + secondsDifference + ' second/s ');


回答2:

Based on the approved answer:

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

    return daysDifference;
}


回答3:

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.