如何舍入秒数:

1 sec - 59 sec1 minute之间

1 min 1 sec-1 min 59 sec->之间舍入到2 m

1h 2 min 1 sec-2 min 59 sec->之间舍入到1h 3 m吗?

2 min 1 sec-2 min 59 sec->之间舍入到3 m吗?

我用图书馆的“时刻”



预期效果:

Date2-date1 =结果四舍五入为整分钟。

date2-date1 = 30 s->舍入到1 m

date2-date1 = 5s->舍入到1 m

date2-date1 = 1m 10s->舍入到2 m

javascript中或moment.js库中可能有一种方法

a = (d1, d2) => {
  let b= moment(d2).diff(d1,"minutes",true)

  return  Math.round(b) * 60;
}


不同的1m 20 s->舍入到2m->没关系

不同的5s->不要舍入到1 m // problem here

最佳答案

您正在搜索Math.ceil()



const a = (d1, d2) => {
  let b = moment(d2).diff(d1, "minutes", true)
  return Math.ceil(b)
}

console.log(a('2019-07-05 10:43:18', '2019-07-05 10:43:18'))
console.log(a('2019-07-05 10:43:18', '2019-07-05 10:43:59'))
console.log(a('2019-07-05 10:43:18', '2019-07-05 10:44:59'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js" integrity="sha256-H9jAz//QLkDOy/nzE9G4aYijQtkLt9FvGmdUTwBk6gs=" crossorigin="anonymous"></script>





更新

Moment现在不支持duration().format()。但是您可以尝试这种解决方法(如果需要,您需要处理数天)



const a = (d1, d2) => {
  let b = moment(d2).diff(d1, "minutes", true)
  let d = moment.duration({
    minutes: Math.ceil(b)
  })
  return moment(d._data).format('H[h] m[m]').replace(/^0h\s|\s0m/, '')
}

console.log(a('2019-07-05 10:43:18', '2019-07-05 10:43:18'))
console.log(a('2019-07-05 10:43:18', '2019-07-05 10:43:59'))
console.log(a('2019-07-05 10:43:18', '2019-07-05 20:44:59'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js" integrity="sha256-H9jAz//QLkDOy/nzE9G4aYijQtkLt9FvGmdUTwBk6gs=" crossorigin="anonymous"></script>





或使用moment-duration-format



const a = (d1, d2) => {
  let b = moment(d2).diff(d1, "minutes", true)

  return moment.duration({
    minutes: Math.ceil(b)
  }).format("d[d] h[h] m[m]", { trim: "both" });
}

console.log(a('2019-07-05 10:43:18', '2019-07-05 10:43:18'))
console.log(a('2019-07-05 10:43:18', '2019-07-05 10:43:59'))
console.log(a('2019-07-05 10:43:18', '2019-07-07 20:44:59'))

<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.js" integrity="sha256-H9jAz//QLkDOy/nzE9G4aYijQtkLt9FvGmdUTwBk6gs=" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/2.3.2/moment-duration-format.min.js" integrity="sha256-M2KULKSJyw+G0068JiMlM9GX4XpLdUButSzBqntKDZM=" crossorigin="anonymous"></script>

09-10 10:57
查看更多