Yahoo
Yahoo

Reputation: 568

Convert value into seconds using javascript moment

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/

Upvotes: 1

Views: 1267

Answers (2)

Lionel Rowe
Lionel Rowe

Reputation: 5926

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

Upvotes: 2

Giovanni Esposito
Giovanni Esposito

Reputation: 11156

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.

Upvotes: 2

Related Questions