首页 > 解决方案 > 如何以秒为单位将时刻对象转换为持续时间?

问题描述

我发现了很多关于将持续时间对象转换为各种格式的信息,但是很难找到关于将时刻对象转换为以秒为单位的持续时间的信息。

这个答案提供了以下解决方案:myVar = moment.duration(myVar).asSeconds()

但是在我的情况下它不起作用,myVar它是 MM:SS 格式而不是 HH:MM:SS 格式,所以我得到了一个异常的结果。知道如何适应我的情况吗?

编辑:这是一些代码

this.totalTimeSimulation = moment(lastActionEndTime, 'mm:ss').add(additionalTimeDuration, 'seconds').format('mm:ss')
this.totalTimeSimulationInSeconds = moment.duration(this.totalTimeSimulation).asSeconds()
console.log(this.totalTimeSimulation)
console.log(this.totalTimeSimulationInSeconds)

在控制台中我看到:

04:00

14400

应该:

04:00

240

因为 4 分钟等于 240 秒,而不是 14400 秒。Moment.js 认为我以 HH:MM:SS 格式给它一个持续时间,而实际上我是以 MM:SS 格式给它的。

标签: momentjs

解决方案


时刻威胁输入,04:00HH:MM

格式是由冒号分隔的小时、分钟、秒字符串,如23:59:59. 天数可以像这样以点分隔符作为前缀7.23:59:59。也支持部分秒23:59:59.999

moment.duration('23:59:59');
moment.duration('23:59:59.999');
moment.duration('7.23:59:59.999');
moment.duration('23:59'); // added in 2.3.0

您可以使用分钟和秒键为输入添加前缀00:或使用构造函数:moment.duration(Object)

const totalTimeSimulation = '04:00'
const totalTimeSimulationInSeconds = moment.duration('00:' + totalTimeSimulation).asSeconds()
console.log(totalTimeSimulation)
console.log(totalTimeSimulationInSeconds)
const parts = totalTimeSimulation.split(':')
const seconds = moment.duration({
  minutes: parts[0],
  seconds: parts[1]}).asSeconds()
console.log(seconds)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>


推荐阅读