momentjs - 如何以秒为单位将时刻对象转换为持续时间?
问题描述
我发现了很多关于将持续时间对象转换为各种格式的信息,但是很难找到关于将时刻对象转换为以秒为单位的持续时间的信息。
这个答案提供了以下解决方案: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 格式给它的。
解决方案
时刻威胁输入,04:00
如HH: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>
推荐阅读
- sql - 如何像另一个表一样排列数据库表?
- swift - 应用程序中的 Swift Firebase 多个数据库
- mysql - 错误:[HY000][1215] 无法添加外键约束
- angular - 如何在 Angular 4 及更高版本的 ngx-select 中获取默认选定值?
- c# - 通过 C# Driver 在 MongoDB 中创建过期索引
- timer - 如何使定时器 irq 在 QEMU 上工作(-machine virt -cpu cortex-a57)
- java - Springboot @EntityScan 不起作用
- android - 无法为“-i ...”找到合适的输出格式
- html - 修改浏览器根调色板
- python - 如何检查 Python 队列中是否存在 obj