0

I am planning to create a chat app, where the message displays relative times like 1 sec ago, 2 mins ago etc.

I have the below code

function timeDifference(current, previous) {

    var msPerMinute = 60 * 1000;
    var msPerHour = msPerMinute * 60;
    var msPerDay = msPerHour * 24;
    var msPerMonth = msPerDay * 30;
    var msPerYear = msPerDay * 365;

    var elapsed = current - previous;

    if (elapsed < msPerMinute) {
         return Math.round(elapsed/1000) + ' seconds ago';   
    }

    else if (elapsed < msPerHour) {
         return Math.round(elapsed/msPerMinute) + ' minutes ago';   
    }

    else if (elapsed < msPerDay ) {
         return Math.round(elapsed/msPerHour ) + ' hours ago';   
    }

    else if (elapsed < msPerMonth) {
        return 'approximately ' + Math.round(elapsed/msPerDay) + ' days ago';   
    }

    else if (elapsed < msPerYear) {
        return 'approximately ' + Math.round(elapsed/msPerMonth) + ' months ago';   
    }

    else {
        return 'approximately ' + Math.round(elapsed/msPerYear ) + ' years ago';   
    }
}

I need to compare the time stamp of users computer and the other user timestamp which are in my database.

If user1 is connecting from the USA and user2 is connecting from Russia, will the timestamps be the same or will they be different? If they're different, what is the way to create relative time?

royhowie
  • 11,075
  • 14
  • 50
  • 67
Vishnu
  • 2,372
  • 6
  • 36
  • 58

1 Answers1

0

Javascript will create a timestamp base on the system its running so for a us system it will use its timezone.

in addition there is a difference between php time and javascript:

startLive = new Date(<?php echo strtotime($start_date)*1000; ?>);

Explanation:

PHP's strtotime function returns a Unix timestamp (seconds since 1-1-1970 at midnight).

Javascript's Date() function can be instantiated by specifying milliseconds since 1-1-1970 at midnight.

So multiply seconds by 1000 and you get milliseconds, which you can use in Javascript.

Pass Datetime/Timestamp from PHP to Javascript by echo

Community
  • 1
  • 1
ChaosClown
  • 367
  • 2
  • 16