如何从 javascript 中的 ZoneDdateTime 获取时差

How to get time difference from ZoneDateTime in javascript

如何获取两个日期时间之间的时差(以秒为单位),一个是来自后端的 ZoneDateTime 形式,另一个是前端收到响应时的当前时间。

后端的响应时间为 -

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: {…}}

从这里如何找到当前时间和这次时间之间的秒数差异?

根据数据计算等效的 ECMAScript 时间值。从当前时间值中减去它,得到以毫秒为单位的差异,例如

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 = (ms%6e4) / 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)})`
  );
});