ManishDalwadi
ManishDalwadi

Reputation: 41

How to convert minutes to time(hh:mm:ss)?

My question is: How to convert minutes to time(hh:mm:ss)?

I have a value with:

decimalMinuteString="1.1783471074380165"

Expected output is: "00:01:10"

How to do with javascript/jquery?

Thanks

Upvotes: 3

Views: 19896

Answers (4)

Vikas Pandey
Vikas Pandey

Reputation: 1

Just use this one line:

new Date(minutes * 60 * 1000).toISOString().substring(11, 19)

For example:

148 minutes = 02:28:00

Upvotes: 0

Z.T
Z.T

Reputation: 485

I needed to convert X minutes to HH:MM (Hours:Minutes), I used the following code to accomplish this:

MINUTES = X; //some integer

var m = MINUTES % 60;

var h = (MINUTES-m)/60;

var HHMM = (h < 10 ? "0" : "") + h.toString() + ":" + (m < 10 ? "0" : "") + m.toString();

Upvotes: 13

Pavel
Pavel

Reputation: 31

One line is:

new Date(minutes * 60 * 1000).toISOString().substr(11, 8);

Upvotes: 3

Siavas
Siavas

Reputation: 5090

A very neat answer has been given by powtac in another question, where seconds were needed to be converted to the same format.

Changing his provided solution to fit your issue, the following prototype function can be used to convert minutes to HH:MM:SS string format.

String.prototype.minsToHHMMSS = function () {
    var mins_num = parseFloat(this, 10); // don't forget the second param
    var hours   = Math.floor(mins_num / 60);
    var minutes = Math.floor((mins_num - ((hours * 3600)) / 60));
    var seconds = Math.floor((mins_num * 60) - (hours * 3600) - (minutes * 60));

    // Appends 0 when unit is less than 10
    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    return hours+':'+minutes+':'+seconds;
}

// Use it as following:
myDecimalNumber.minsToHHMMSS();

See the working code in the snippet below:

String.prototype.minsToHHMMSS = function () {
    var mins_num = parseFloat(this, 10); // don't forget the second param
    var hours   = Math.floor(mins_num / 60);
    var minutes = Math.floor((mins_num - ((hours * 3600)) / 60));
    var seconds = Math.floor((mins_num * 60) - (hours * 3600) - (minutes * 60));

    // Appends 0 when unit is less than 10
    if (hours   < 10) {hours   = "0"+hours;}
    if (minutes < 10) {minutes = "0"+minutes;}
    if (seconds < 10) {seconds = "0"+seconds;}
    return hours+':'+minutes+':'+seconds;
}

var decimalMinuteString = '1.1783471074380165';

var timeString = decimalMinuteString.minsToHHMMSS();

var input = document.getElementById('input');
var output = document.getElementById('output');
input.innerText = decimalMinuteString;
output.innerText = timeString;
<p>
  Input: <span id="input"></span> 
</p>
<p>
  Output: <span id="output"></span>  
</p>

If this solution helped you, please upvote firstly powtac's answer as it is the base of the answer.

Upvotes: 4

Related Questions