1

I am facing a problem to Get Two Time Different Globally. I need diff time format days: Hours: Minutes: Seconds. Everything is ok but problem in hour. For this example hour should be 0 hour but it return 6 hours..

function getTimeDiff(join, lastSeen) {

  let t1 = new Date(join).getTime(),
    t2 = new Date(lastSeen).getTime(),
    milliseconds = 0,
    time = '';
  if (isNaN(t1) || isNaN(t2)) return '';
  if (t1 < t2) {milliseconds = t2 - t1;}
  else {milliseconds = t1 - t2;}
  var days = Math.floor(milliseconds / 1000 / 60 / (60 * 24));
  var date_diff = new Date(milliseconds);
  if (days > 0) time += days + 'd ';
  console.log('join: ', join, ' - ', 'lastseen:', lastSeen);
  console.log('Diff = ', milliseconds);
  console.log('Standard Time : ', date_diff);
  console.log('Hours: ', date_diff.getHours());
  console.log('Minutes: ', date_diff.getMinutes());
  console.log('Secounds: ', date_diff.getSeconds());
  if (date_diff.getHours() > 0) time += date_diff.getHours() + 'h ';
  if (date_diff.getMinutes() > 0) time += date_diff.getMinutes() + 'm ';
  if (date_diff.getSeconds() > 0) time += date_diff.getSeconds() + 's ';
  console.log('Result: ', time);
  return time;

}

console.log(getTimeDiff(1589911275699, 1589911365116));

The output result:

**

1589911275699 " -- " 1589911365116
join:  1589911275699  -  lastseen: 1589911365116
Diff =  89417
Standard Time :  Thu Jan 01 1970 06:01:29 GMT+0600 (Bangladesh Standard Time)
Hours:  6 // Result should be 0
Minutes:  1
Secounds:  29
Result:  6h 1m 29s // 0h 1m 29s

**

Here already have some post but same problem https://stackoverflow.com/a/18103175

Shapon Pal
  • 1,098
  • 3
  • 16
  • 27
  • Why are you converting to Date objects? Just subtract the two time values and convert the difference to day, hrs, mins, etc. – RobG May 20 '20 at 00:37

3 Answers3

1

You don't need to convert to Date objects, the time vlaues you have are sufficient. E.g.

function getTimeDiff(t0, t1) {
  let z = n => (n<10?'0':'')+n;
  let diff = t1 - t0;
  let sign = diff < 0? '-':'+';
  diff = Math.abs(diff);
  let h = diff / 3.6e6 | 0;
  let m = (diff % 3.6e6) / 6e4 | 0;
  let s = (diff % 6e4) / 1e3 | 0;
  
  return `${sign}${h}:${z(m)}:${z(s)}`; 
}

let join = 1589911275699;
let lastseen = 1589911365116;
console.log(`The time difference between 
${new Date(join)} and
${new Date(lastseen)} is
${getTimeDiff(join, lastseen)}`);

Note that the difference in the generated timestamps is different to the difference in the time values as conversion to timestamps truncates the milliseconds (decimal seconds).

Converting to Date objects does nothing useful, since:

new Date(join).getTime() === join

where join is a number in the range ±8.64e15. That gives a range of 100 million days either side of 1 Jan 1970.

RobG
  • 142,382
  • 31
  • 172
  • 209
0

When you construction date object (new Date(milliseconds)) it create date object in your timezone, (you have +6 GMT as I think) so you get +6 hours more.

Simple fix is to apply timezone offset:

var hours = date_diff.getHours() + new Date().getTimezoneOffset()/60; if (hours > 0) time += hours + 'h ';

But this will not cover timezones with half of hour offset https://en.wikipedia.org/wiki/Time_zone#/media/File:Solar_time_vs_standard_time.png For example Australia have +9:30 offset timezone

It's better to manullay get time diff:

var milliseconds = 89417;
var hours = Math.floor(milliseconds/1000/60/60);
var minutes = Math.floor((milliseconds - hours*1000*60*60)/1000/60);
var seconds = Math.floor((milliseconds - hours*1000*60*60 - minutes*1000*60)/1000);

console.log(hours, minutes, seconds);

PS:

I've recommend to use moment.js for calculating time diff, check this https://stackoverflow.com/a/18624295/676611

dark_gf
  • 684
  • 5
  • 15
  • How to do it Globally? Not depend on time zone – Shapon Pal May 19 '20 at 19:01
  • @ShaponPal sry bad solution it will not work when milliseconds + new Date().getTimezoneOffset()*60*1000 will be less then 0, I will update soon – dark_gf May 19 '20 at 19:12
  • "*When you construction date object (new Date(milliseconds)) it create date object in your timezone*" is incorrect, the value is treated as UTC. ECMAScript date objects don't have a timezone, they are effectively always UTC, conversion to local values is through *get\** and various *to\*String* methods. – RobG May 19 '20 at 23:58
0

This is a modified code snippet of @RobG

 function getTimeDiff(t0, t1) {
        var s,m,h,d,tDiff="";
        let z = n => (10 > n?'0':'')+n;
        let diff = t1 - t0;
        if(diff < 0) {return "0s"};
        diff = Math.abs(diff);
        d = Math.floor(diff / 86.4e6 | 0);
        h = Math.floor(diff / 3.6e6 | 0);
        if(d > 0){
            tDiff += d + "d ";
            h -= (d * 24);
        }
        m = Math.floor((diff % 3.6e6) / 6e4 | 0);
        s = Math.floor((diff % 6e4) / 1e3 | 0);
        if(h > 0) {tDiff += h + "h ";}
        if(m > 0) {tDiff += m + "m ";}
        tDiff += s + "s";
        return tDiff;
    }

let join = 1589645159314;
//let join = new Date(Date.now() - (1 * 22 * 60 * 60 * 1000)).getTime();
//let lastseen = 1589911365116;
let lastseen = Date.now();
console.log(`The time difference between 
${new Date(join)} and
${new Date(lastseen)} is
${getTimeDiff(join, lastseen)}`);

function getTimeDiff(t0, t1) {
  let z = n => (n<10?'0':'')+n;
  let diff = t1 - t0;
  let sign = diff < 0? '-':'+';
  diff = Math.abs(diff);
  let h = diff / 3.6e6 | 0;
  let m = (diff % 3.6e6) / 6e4 | 0;
  let s = (diff % 6e4) / 1e3 | 0;
  
  return `${sign}${h}:${z(m)}:${z(s)}`; 
}

let join = 1589911275699;
let lastseen = 1589911365116;
console.log(`The time difference between 
${new Date(join)} and
${new Date(lastseen)} is
${getTimeDiff(join, lastseen)}`);
Shapon Pal
  • 1,098
  • 3
  • 16
  • 27