Home > Back-end >  How to get time difference from ZoneDateTime in javascript
How to get time difference from ZoneDateTime in javascript

Time:02-12

How can I get the time difference in seconds between two date-times one is from the backend in the form of ZoneDateTime and the other will be the current time at the frontend while response get received.

Response time from backend is -

callStartTime:{
chronology: {id: 'ISO', calendarType: 'iso8601'}
dayOfMonth: 8
dayOfWeek: "TUESDAY"
dayOfYear: 39
hour: 16
minute: 15
month: "FEBRUARY"
monthValue: 2
nano: 240000000
offset: {totalSeconds: 19800, id: ' 05:30', rules: {…}}
second: 29
year: 2022
zone: {id: 'Asia/Calcutta', rules: {…}}

From this How can I find the difference between current time and this time in seconds ?

CodePudding user response:

Calculate the equivalent ECMAScript time value from the data. Subtract that from the current time value and you have the difference in milliseconds, e.g.

function getTimeDiff(data, date = new Date()) {
  let utc = new Date(Date.UTC(
      data.year, 
      data.monthValue - 1,
      data.dayOfMonth,
      data.hour,
      data.minute,
      data.second
  ) - data.offset.totalSeconds*1e3);
  return date - utc;
}

function msToTime(ms) {
  let days = ms / 8.64e7 | 0;
  let hrs = (ms%8.64e7) / 3.6e6 | 0;
  let mins = (ms%3.6e6) / 6e4 | 0;
  let secs = (msn4) / 1e3 | 0;
  let z = n => (n<10? '0':'')   n;
  return `${days? days   ' day'   (days == 1? ' ' : 's ') : ''}${z(hrs)}:`  
         `${z(mins)}:${z(secs)}`;
}

let callStartTime = {
  chronology: {id: 'ISO', calendarType: 'iso8601'},
  dayOfMonth: 8,
  dayOfWeek: "TUESDAY",
  dayOfYear: 39,
  hour: 16,
  minute: 15,
  month: "FEBRUARY",
  monthValue: 2,
  nano: 240000000,
  offset: {totalSeconds: 19800, id: ' 05:30', rules: {}},
  second: 29,
  year: 2022,
  zone: {id: 'Asia/Calcutta', rules: {}}
};

['2022-02-08T16:15:29 05:30', // 0
 null // now
].forEach(ts => {
  let data = callStartTime;
  let compDate = ts? new Date(ts) : new Date();
  let diffMs = getTimeDiff(data, compDate);
  console.log(`${ts || compDate.toISOString()} : `  
              `${diffMs} ms (${msToTime(diffMs)})`
  );
});

  • Related