【问题标题】:Convert value into seconds using javascript moment使用javascript时刻将值转换为秒
【发布时间】:2020-12-07 19:31:52
【问题描述】:

有没有办法使用moment.js 将var timeValue = '65' 格式化为01:05?它更容易格式化为 ('HH:MM:SS') 但将变量传递为 65 并转换为 ('mm:ss') 给我的响应是 '01:00' 而不是 '01:05',

查看

<div id="app">
  <p>
  Time is {{roomTime}}
  </p>
  <br/>
  <p>
  How to make it display 01:05 not 01:00
  </p>
 </div>

脚本

new Vue({
  el: "#app",
  data() {
    return{
     roomTime: '',
    }
  },
  mounted: function(){
    var timeValue = '65'; /** As 65 is 1 minute and 5 seconds **/
    var formatTime = moment(timeValue).format("MM:SS");
    /** How to make 65 to be display as 01:05 **/
 
    this.roomTime = formatTime;
  },
  methods: {
    toggle: function(todo){
        todo.done = !todo.done
    }
  }
})

下面是我在JSFIDDLE

中的代码参考

https://jsfiddle.net/ujjumaki/2x1ndpja/13/

【问题讨论】:

标签: javascript vue.js momentjs


【解决方案1】:

Ciao,你可以这样使用moment

var timeValue = '65';
moment().startOf('day')
    .seconds(timeValue)
    .format('mm:ss'))

在一天的开始时获取当前日期 (moment().startOf('day')),添加 timeValue 秒 (.seconds(timeValue)),最后格式化 (.format('mm:ss'))。

输出将是01:05Here您的代码已修改。

【讨论】:

  • 为 moment.Js 学习了一个新的 this 作为 startOf('day')。谢谢它现在工作。
  • 没问题。祝你有美好的一天:)
【解决方案2】:

moment(String)uses the following parsing logic:

首先检查字符串是否匹配已知的 ISO 8601 格式,然后我们检查字符串是否匹配 RFC 2822 日期时间格式,然后如果未找到已知格式则回退到 new Date(string)

"65" 恰好被解析为 1 月 1 日 1 月 1 日的午夜 UTC65。如果格式化为mm:ss,则为00:00

moment(...) 也可以带数字,在这种情况下为it's treated as a unix timestamp in milliseconds

因此,您可以使用以下内容:

const seconds = 65

const ms = seconds * 1000

moment(ms).format('mm:ss')

【讨论】:

    猜你喜欢
    • 2016-12-23
    • 2015-07-04
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    • 2011-09-01
    • 1970-01-01
    • 2010-11-22
    相关资源
    最近更新 更多