6

I'm trying to calculate time when user open a specific screen,When he enters in the screen the the time starts and when I exit from the screen the time stops and gives the time spend on the screen

here is my code:

componentDidMount = () => {
    
    let date = new Date();
    let hours = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    this.setState({
      startHour: hours,
      startMin: minutes,
      startSeconds: seconds,
    });
}

Here is ComponentWillunmount

componentWillUnmount() {

let date = new Date();
let endHours = date.getHours();
let endMinutes = date.getMinutes();
let endSeconds = date.getSeconds();
console.log(`${endHours}:${endMinutes}:${endSeconds}`);
console.log(
  `${this.state.startHour}:${this.state.startMin}:${this.state.startSeconds}`,
);

}

Zaid Qureshi
  • 155
  • 3
  • 12
  • 2
    So what have you tried and where are you having problems? You have only told us your objective but haven't provided any code attempts to solve your issue or any of the research you have done – charlietfl Aug 26 '20 at 05:38
  • I've added the code you can check it – Zaid Qureshi Aug 26 '20 at 06:01
  • Ok that's part of it....you still haven't explained where you are having problems – charlietfl Aug 26 '20 at 06:06
  • i want to calculate difference between the start time and end time,I don't know how to do that – Zaid Qureshi Aug 26 '20 at 06:07
  • 2
    Simplest is just store Date.now() in mount and then subtract that from Date.now() in unmount.... difference will be in ms...do the math to get into whatever format you want it in – charlietfl Aug 26 '20 at 06:08
  • Also can subtract one new Date from another and result will also be in ms. `new Date('2020-01-02')-new Date('2020-01-01')// returns 86400000` – charlietfl Aug 26 '20 at 06:11

3 Answers3

2

When he enters in the screen the the time starts and when I exit from the screen the time stops and gives the time spend on the screen

It's a very important Feature Request by many for web 2.0 applications. So, I write a detailed, working and simple solution on the subject here.

You are requesting a feature already created for this workflow. It's a plugin you can include in any website. It's none other than time-on-site tracking in timeonsite.js

Look at the following code (Use latest version; don't just copy/paste),

<head>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/timeonsite/1.2.0/timeonsitetracker.js"></script>

<script>
var config = {
    // track page by seconds. Default tracking is by milliseconds
    trackBy: 'seconds',

    trackHistoryChange: true, //Single-page React/Angular app

    callback: function(data) { /* callback denotes your data tracking is real-time */
        console.log(data);
        var endPointUrl = 'http://example.com' //Replace with your actual backend API URL http://localhost/tos
        if (data && data.trackingType) {
            if (data.trackingType == 'tos') {
                if (Tos.verifyData(data) != 'valid') {
                    console.log('Data abolished!');
                    return; 
                }
            }

            // make use of sendBeacon if this API is supported by your browser.
            if (navigator && typeof navigator.sendBeacon === 'function') {
                data.trasferredWith = 'sendBeacon';
                var blob = new Blob([JSON.stringify(data)], {type : 'application/json'});
                navigator.sendBeacon(endPointUrl, blob);
            }
        }
    }
};
var Tos;
if (TimeOnSiteTracker) {
    Tos = new TimeOnSiteTracker(config);
}
</script>

</head>

Then, when you refresh, reload or navigate the React app page,

You'll see following object directly saved into your table/printed in browser console. Select "persist" in logs,

{
    TOSId: 1129620185532,
    TOSSessionKey: "14802525481391382263",
    TOSUserId: "anonymous",
    title: "Test application - Home page",
    URL: "http://nature-blogs/pages/home.php"
    entryTime: "2021-11-27 13:15:48.663",
    currentTime: "2021-11-27 13:17:31.663",
    timeOnPage: 103,
    timeOnSite: 103,
    timeOnPageTrackedBy: "second",
    timeOnPageByDuration: "0d 00h 01m 43s",
    timeOnSiteByDuration: "0d 00h 01m 43s",
    trackingType: "tos",
}

As you can see, the actions

  • "entryTime" is captured
  • "exitTime" is captured in seconds/milliseconds depending upon configuration
  • "type:time_on_site" is captured
  • "timeOnPage" is captured // individual page time
  • "timeOnSite" is captured // session overall page time

What else you need? Since it's stored in SQL DB table, you can do analysis/reporting queries yourself. The same is the case for NoSQL as well. Timeonsite.js is supporting both RDBMS and NoSql DB types.

On top of it, 1.Minimize tab, 2.Inactive tab and 3.Switch tab's idle time are all computed and ignored automatically by the tracker itself.

The only thing to note in configuration part is,

trackHistoryChange: true

If the page routing depends on Location Hash or also known as single-page app, include this setting. On the other hand if your web application is a normal page like Wikipedia, avoid setting this line. You are done. For showing the real-time stay time on screen, check this SO post. It's using Jquery to show the results. You can customize it for your React app.

This tracker can be plugged-in in any library not only in React app but also Angular, Jquery, MooTools etc. since it's plain vanilla JS library.

Let me know if you need more input on the subject. I can assist you on this.

webblover
  • 1,196
  • 2
  • 12
  • 30
  • I also found a react only way of integrating the tracker in this post https://stackoverflow.com/questions/73956768/integrating-timeonsite-js-on-a-basic-reactjs-app-and-correct-way-to-show-live-ti – webblover Nov 30 '22 at 09:40
0

I'm not a react dev but this is fairly simple and this would be the approach.

componentDidMount = () => {
   /* On init set the start time
      Also: multiplying new Date() by 1 will return a timestamp
    */
   this.startTime = new Date() * 1;
}

componentWillUnmount() {
    /* Then on view destroy set the endTime */
    let endTime = new Date() * 1;
    /* Subtract the end time with start time, since endTime has greater value. The result
     is the difference between start and end time in milliseconds.
     */
    let elapsed = endTime - this.startTime;
    /* The result is in milliseconds so:
       elapsed / 1000 -> is seconds
       elapsed / 1000 / 60 -> is minutes
       etc.
     */
);
masterpreenz
  • 2,280
  • 1
  • 13
  • 21
-3

I agree with @masterpreenz

componentDidMount = () => {
   this.startTime = new Date() * 1;
}

componentWillUnmount() {
    let endTime = new Date() * 1;
    let elapsed = endTime - this.startTime;
    $('viewPageStayTime').html('You spent '+elaspsed+ ' duration.'); 
);
  • 1
    This is just copycat post from copied from @msterpreenz and no useful information provided in this code. – webblover Sep 01 '22 at 06:51