javascript 24小时格式的平均时间

rvpgvaaj  于 2023-04-04  发布在  Java
关注(0)|答案(1)|浏览(151)

我需要平均时间从24小时的时间.我想包括24小时秒时,午夜是00:00:00AM.目前,与下面的信息,我会得到20:46:00公元前00:00:00不计算到86400.我是新的Javascript和学习,因为我去所以任何帮助是赞赏.谢谢.

// Defined variables from Object Item groups

var totalTime = null;

var Bed_1 = 23:00:00

var Bed_2 = 22:30:00

var Bed_3 = 23:00:00

var Bed_4 =21:44:00

var Bed_5 = 23:00:00

var Bed_6 = 23:00:00

var Bed_7 = 21:46:00

var Bed_8 = 22:45:00

var Bed_9 = 22:40:00

var Bed_10 = 00:00:00

var Bed_11 = 23:44:00

var Bed_12 = 22:07:00


var newValue = 12

 

//This code section is spliting the array coming from JSON for conversion to seconds then back to time.

var a = Bed_1.split(":")

var seconds1 = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);

var b = Bed_2.split(":");

var seconds2 = (+b[0]) * 60 * 60 + (+b[1]) * 60 + (+b[2]);

var c = Bed_3.split(":");

var seconds3 = (+c[0]) * 60 * 60 + (+c[1]) * 60 + (+c[2]);

var d = Bed_4.split(":")

var seconds4 = (+d[0]) * 60 * 60 + (+d[1]) * 60 + (+d[2]);

var e = Bed_5.split(":");

var seconds5 = (+e[0]) * 60 * 60 + (+e[1]) * 60 + (+e[2]);

var f = Bed_6.split(":");

var seconds6 = (+f[0]) * 60 * 60 + (+f[1]) * 60 + (+f[2]);

var g = Bed_7.split(":");

var seconds7 = (+g[0]) * 60 * 60 + (+g[1]) * 60 + (+g[2]);

var h = Bed_8.split(":")

var seconds8 = (+h[0]) * 60 * 60 + (+h[1]) * 60 + (+h[2]);

var i = Bed_9.split(":");

var seconds9 = (+i[0]) * 60 * 60 + (+i[1]) * 60 + (+i[2]);

var j = Bed_10.split(":");

var seconds10 = (+j[0]) * 60 * 60 + (+j[1]) * 60 + (+j[2]);

var k = Bed_11.split(":")

var seconds11 = (+k[0]) * 60 * 60 + (+k[1]) * 60 + (+k[2]);

var l = Bed_12.split(":");

var seconds12 = (+l[0]) * 60 * 60 + (+l[1]) * 60 + (+l[2]);

var date = new Date(1970, 0, 1)

date.setSeconds((seconds1 + seconds2 + seconds3 + seconds4 + seconds5 + seconds6 + seconds7 + seconds8 + seconds9 + seconds10 + seconds11 + seconds12) / newValue);

var totalTime = date.toTimeString().replace(/.*(\d{2}:\d{2}:\d{2}).*/, "$1");

return { value: totalTime, measurementUnitName: "HH:mm:ss" };

我尝试检查数组中的0,然后使用push方法将24转换为秒。

ac1kyiln

ac1kyiln1#

假设你想让00:00:00表示一天的结束(午夜),试试这样的方法:

const bed_time = [
  "23:00:00",
  "22:30:00",
  "23:00:00",
  "21:44:00",
  "23:00:00",
  "23:00:00",
  "21:46:00",
  "22:45:00",
  "22:40:00",
  "00:00:00",
  "23:44:00",
  "22:07:00",
];

const hhmmss_to_secs = (hhmmss) => {
  const [hh, mm, ss] = hhmmss.split(':').map(Number);
  return hh * 3600 + mm * 60 + ss || 24 * 3600;
};

const bed_secs = bed_time.map(hhmmss_to_secs);

const avg_secs = bed_secs.reduce((a, b) => a + b) / bed_secs.length;

const avg_hhmmss = new Date(avg_secs * 1000).toISOString().substr(11, 8);

console.log(avg_hhmmss);

相关问题