Winnemucca
Winnemucca

Reputation: 3458

How to convert number to time format in javascript

I am trying to convert the number 20 into minutes with moment js. I need

21 to to look like 21:00

This way for my set interval the timer will show 19:58 to 0:01.

I had tried

  var x = 1260000;
  var d = moment.duration(x, 'milliseconds');
  var hours = Math.floor(d.asHours());
  var mins = Math.floor(d.asMinutes()) - hours * 60;

This still leaves me with 21. I am not sure how to get the minutes form.

This seems like it shoud be a short fix. Any help is greatly appreciated.

Upvotes: 2

Views: 26938

Answers (4)

stella06700
stella06700

Reputation: 77

var number = 15;
moment(number.toString(),"LT")

output 15:00

other method var value = 6.8 (exemple : 34/5 (34 hours of work / 5 days)) /** * Convertion d'un nombre en Moment * @param value */ convertNumberToMoment(value: number): moment.Moment {

    var hours = Math.floor(value);
    var minutes = Math.round((value % 1)*100)/100;

    return moment(hours + ':' + minutes * 60 + '0',"LT");       
}

output 6:48

Upvotes: 4

VincenzoC
VincenzoC

Reputation: 31482

You can use moment-duration-format plug-in and duration subtract method.

The plug-in lets you format duration object and with the subtract method you can modify duration value.

Here a working example that may help you:

var $container = $('#timer');

var x = 1260000;
var d = moment.duration(x, 'milliseconds');

var intervalId = setInterval(function(){
  d.subtract(1, 's');
  if( d.seconds() >= 0 ){
    var timer = d.format('m:ss', { trim: false });
    $container.html(timer);
  } else {
    clearInterval(intervalId);
  }
}, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script>

<div id="timer"></div>

Upvotes: 1

Ivan Shmidt
Ivan Shmidt

Reputation: 173

How to create a new moment object from hours-string and to display it as HH:MM :

var input = '21'; moment(input,'HH').format('HH:mm'); // 21:00

Upvotes: 1

Abhishek Priyadarshi
Abhishek Priyadarshi

Reputation: 581

var moment = require("moment")
var x = 1260000;
var d = moment.duration(x, 'milliseconds');
moment(d.asMinutes(),'mm').format('mm:ss');

Upvotes: 0

Related Questions