1

Is there a way to format var timeValue = '65' into 01:05 using moment.js? Its easier to format as ('HH:MM:SS') but passing a variable as 65 and converting into ('mm:ss') gives me response as '01:00' not '01:05',

View

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

Script

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
    }
  }
})

Below is my code reference in JSFIDDLE

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

Yahoo
  • 558
  • 11
  • 34
  • 2
    Does this answer your question? [How to convert seconds to HH:mm:ss in moment.js](https://stackoverflow.com/questions/31337370/how-to-convert-seconds-to-hhmmss-in-moment-js) – Ajeet Eppakayala Aug 18 '20 at 15:17
  • Moment has a concept of [durations](https://momentjs.com/docs/#/durations/) that could be leveraged to this end. Unfortunately, the ability to [format a duration](https://stackoverflow.com/questions/13262621/how-do-i-use-format-on-a-moment-js-duration) has been missing for eight years or more. There is a [github issue](https://github.com/moment/moment/issues/463) requesting the formatting feature which has some alternative approaches and workarounds. – Alexander Nied Aug 18 '20 at 15:22

2 Answers2

2

Ciao, you could use moment in this way:

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

Get the current date at the start of the day (moment().startOf('day')), add timeValue seconds (.seconds(timeValue)) and finally format (.format('mm:ss')).

The output will be 01:05. Here your code modified.

Giovanni Esposito
  • 10,696
  • 1
  • 14
  • 30
2

moment(String) uses the following parsing logic:

first check if the string matches known ISO 8601 formats, we then check if the string matches the RFC 2822 Date time format before dropping to the fall back of new Date(string) if a known format is not found

"65" happens to be parsed as midnight UTC on Jan 1st 1965. If formatted as mm:ss, this gives 00:00.

moment(...) can also take a number, in which case it's treated as a unix timestamp in milliseconds.

You can therefore use the following:

const seconds = 65

const ms = seconds * 1000

moment(ms).format('mm:ss')
Lionel Rowe
  • 5,164
  • 1
  • 14
  • 27