【问题标题】:How to convert a moment object into a duration in seconds?如何将时刻对象转换为以秒为单位的持续时间?
【发布时间】:2020-01-10 11:11:10
【问题描述】:

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

This answer 提供以下解决方案: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 格式给出的。

【问题讨论】:

  • 您使用的是哪个版本的时刻? Moment docs 声明从 2.3.0 (moment.duration('23:59'); // added in 2.3.0) 开始支持 MM:SS。可以提供minimal reproducible example吗?
  • 使用 2.24,也许是这样?现在会更新,看看进展如何
  • 你能提供一个显示你的问题的sn-p吗? myVar 的值是多少?你会得到哪个结果?预期的结果是什么?
  • 对不起,我的第一条评论是错误的,像04:00这样的威胁输入为HH:MM,您可以在04:00前加上00:(例如moment.duration('00:' + this.totalTimeSimulation))或使用moment.duration(Object)构造函数使用minutesseconds 键。

标签: momentjs


【解决方案1】:

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>

【讨论】:

    猜你喜欢
    • 2021-12-12
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 2020-02-14
    • 2016-11-05
    • 1970-01-01
    • 2013-05-20
    • 2020-05-03
    相关资源
    最近更新 更多