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>
}
4
  • 2
    What format is the "time stamp", ISO8601? And the non–timestamp string looks like…? Commented May 27, 2013 at 6:16
  • 1
    var diff=Math.abs(date1-date2); Commented May 27, 2013 at 6:17
  • @elclanrs—I think maybe there's some parsing first. Commented 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. Commented May 27, 2013 at 6:41

6 Answers 6

74

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 ');
}
Sign up to request clarification or add additional context in comments.

5 Comments

what if I needed the current time in date1. Will var date1=new Date.getTime(); do the trick?
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?
var date = new Date(Date.parse(YourstringDate.replace(/-/g, " ")));
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?
format temp_date to some Date format like dd/MM/yyy or dd/MMM/yyyy and then try the same code
34

Based on the approved answer:

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

    return daysDifference;
}

1 Comment

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.
6

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)

2 Comments

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();
thanks @wakqasahmed. Updated the answer with your inputs.
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.

Comments

0

You can use this package. @ask-imon/time_diff_calc

// Import the function and FormatTypes - assuming they are in the same file
const { timeDiffCalc, FormatTypes } = require('@ask-imon/time_diff_calc');

// Example timestamps
const timestamp1 = "2022-01-01T00:00:00Z";
const timestamp2 = "2023-01-02T12:30:45Z";

// Calculate the difference in a specific format

// To get the difference in Milliseconds
const differenceInMilliseconds = timeDiffCalc(timestamp1, timestamp2, FormatTypes.MILLISECOND);
console.log(`Difference in Milliseconds: ${differenceInMilliseconds}`);

// To get the difference in Seconds
const differenceInSecond = timeDiffCalc(timestamp1, timestamp2, FormatTypes.SECOND);
console.log(`Difference in Seconds: ${differenceInSecond}`);

// To get the difference in Minutes
const differenceInMinutes = timeDiffCalc(timestamp1, timestamp2, FormatTypes.MINUTE);
console.log(`Difference in Minutes: ${differenceInMinutes}`);

// To get the difference in Hours (Approx.)
const differenceInHours = timeDiffCalc(timestamp1, timestamp2, FormatTypes.HOUR);
console.log(`Difference in Hours: ${differenceInHours}`);

// To get the difference in Day (Approx.)
const differenceInDays = timeDiffCalc(timestamp1, timestamp2, FormatTypes.DAY);
console.log(`Difference in Days: ${differenceInDays}`);

// To get the difference in Weeks (Approx.)
const differenceInWeeks = timeDiffCalc(timestamp1, timestamp2, FormatTypes.WEEK);
console.log(`Difference in Weeks: ${differenceInWeeks}`);

// To get the difference in Months (Approx.)
const differenceInMonths = timeDiffCalc(timestamp1, timestamp2, FormatTypes.MONTH);
console.log(`Difference in Months: ${differenceInMonths}`);

// To get the difference in Years (Approx.)
const differenceInYears = timeDiffCalc(timestamp1, timestamp2, FormatTypes.YEAR);
console.log(`Difference in Years: ${differenceInYears}`);

// To get the difference in DHMS (Days, Hours, Minutes, Seconds)
const differenceInDHMS = timeDiffCalc(timestamp1, timestamp2, FormatTypes.DHMS);
console.log(`Difference in DHMS: ${differenceInDHMS}`);

// To get a detailed breakdown
const detailedDifference = timeDiffCalc(timestamp1, timestamp2, FormatTypes.DETAIL);
console.log(`Detailed difference: ${detailedDifference}`);

Comments

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

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.