James Moore
James Moore

Reputation: 3617

Javascript seconds to minutes and seconds

This is a common problem but I'm not sure how to solve it. The code below works fine.

var mind = time % (60 * 60);
var minutes = Math.floor(mind / 60);
         
var secd = mind % 60;
var seconds = Math.ceil(secd);

However, when I get to 1 hour or 3600 seconds it returns 0 minutes and 0 seconds. How can I avoid this so it returns all the minutes?

Upvotes: 278

Views: 418704

Answers (30)

Harsh Patel
Harsh Patel

Reputation: 1334

console.log(mmSS(01), mmSS(60), mmSS(61)); // 00:01, 1:00, 1:01
console.log(mmSS(01, true), mmSS(5, true), mmSS(5.5, true)); // mins: 01:00, 5:00, 5:30
console.log(mmSS(119), mmSS(120), mmSS(121)); // 1:59, 2:00, 2:01
console.log(mmSS(599), mmSS(600), mmSS(601)); // 9:59, 10:00, 10:01
console.log(mmSS(3599), mmSS(3600), mmSS(3601)); // 59:59, 1:00:00, 1:00:01
console.log(mmSS(35999), mmSS(36000), mmSS(36001)); // 9:59:59, 10:00:00, 10:00:01


function mmSS(duration, isValueInMinsFormat = false) 
{
  if (isValueInMinsFormat) {
    // Convert minutes to seconds
    duration *= 60;
  }

  // Calculate minutes and seconds
  const minutes = Math.floor(duration / 60);
  const seconds = duration % 60;

  // Format the result as MM:SS
  return `${String(minutes).padStart(2, '0')}:${String(seconds).padStart(2, '0')}`;
}


For Convert seconds into HH:MM:SS Refer this Stackoverflow QueAns

Upvotes: 0

Sadegh Maasoomi
Sadegh Maasoomi

Reputation: 300

const totalSeconds = 565;

// 👇️ get the number of full minutes

const minutes = Math.floor(totalSeconds / 60);

// 👇️ get the remainder of the seconds

const seconds = totalSeconds % 60;

function padTo2Digits(num) {
  return num.toString().padStart(2, '0');
}

// ✅ format as MM:SS

const result = `${padTo2Digits(minutes)}:${padTo2Digits(seconds)}`;
console.log(result); // 👉️ "09:25"

Upvotes: 0

Robin Métral
Robin Métral

Reputation: 3209

If you're after a formatted mm:ss time string, you can use the Date constructor and toLocaleTimeString():

const seconds = 157;

const timeString = new Date(seconds * 1000).toLocaleTimeString([], {
  minute: "numeric",
  second: "2-digit",
})

console.log(timeString);

Note that:

  • we create a new Date object using milliseconds, seconds * 1000: the Date constructor accepts a timestamp. Effectively, we're creating a date that is a few minutes after January 1st, 1970, 00:00:00 UTC. (But day doesn't matter, since we only use time)
  • the first parameter of toLocaleTimeString receives a string or array of locales. If left undefined, the user agent's default locale will be used
  • the second parameter takes a DateTimeFormat options object. In our case, if we want mm:ss (without leading zero for minutes), we pass { minute: "numeric", second: "2-digit" }. (If you're still seeing a leading zero for minutes, refer to this question and this answer.)

Upvotes: 2

Ids Klijnsma
Ids Klijnsma

Reputation: 462

2023 update:

To add leading zeros, I would just do:

const secondsToMinSecPadded = time => {
  const minutes = `${Math.floor(time / 60)}`.padStart(2, "0");
  const seconds = `${time - minutes * 60}`.padStart(2, "0");
  return `${minutes}:${seconds}`;
};


console.log(secondsToMinSecPadded(241));

Nice and short

Upvotes: 22

Ranvijay Kumar Singh
Ranvijay Kumar Singh

Reputation: 579

This Workes for Me

 const start_date=moment().subtract(1,"days")
 const end_date=moment()

 const diff = end_date.diff(start_date, "seconds");
 var mind = diff % (60 * 60);

 const hours = Math.floor(diff / (60 * 60));
 const minutes = Math.floor(mind / 60);
 var seconds = Math.ceil(mind % 60);

 console.log("Diff===>", diff, hours, minutes, seconds);

..................Happy Codding...............

Upvotes: 0

Vishal
Vishal

Reputation: 20617

Another fancy solution:

function fancyTimeFormat(duration) {
  // Hours, minutes and seconds
  const hrs = ~~(duration / 3600);
  const mins = ~~((duration % 3600) / 60);
  const secs = ~~duration % 60;

  // Output like "1:01" or "4:03:59" or "123:03:59"
  let ret = "";

  if (hrs > 0) {
    ret += "" + hrs + ":" + (mins < 10 ? "0" : "");
  }

  ret += "" + mins + ":" + (secs < 10 ? "0" : "");
  ret += "" + secs;

  return ret;
}

console.log(
  fancyTimeFormat(1),
  fancyTimeFormat(10),
  fancyTimeFormat(100),
  fancyTimeFormat(1000),
  fancyTimeFormat(10000),
);

~~ is a shorthand for Math.floor, see this link for more info

Upvotes: 177

Gumbo
Gumbo

Reputation: 655309

To get the number of full minutes, divide the number of total seconds by 60 (60 seconds/minute):

const minutes = Math.floor(time / 60);

And to get the remaining seconds, multiply the full minutes with 60 and subtract from the total seconds:

const seconds = time - minutes * 60;

Now if you also want to get the full hours too, divide the number of total seconds by 3600 (60 minutes/hour · 60 seconds/minute) first, then calculate the remaining seconds:

const hours = Math.floor(time / 3600);
time = time - hours * 3600;

Then you calculate the full minutes and remaining seconds.

Bonus:

Use the following code to pretty-print the time (suggested by Dru):

function str_pad_left(string, pad, length) {
  return (new Array(length + 1).join(pad) + string).slice(-length);
}

const finalTime = str_pad_left(minutes, '0', 2) + ':' + str_pad_left(seconds, '0', 2);

Upvotes: 469

Paul
Paul

Reputation: 471

if you need to work with the result easily later this is what I use:

function seconds2hms(seconds, milliseconds) {
if(milliseconds) {
    seconds = Math.floor(seconds/1000);
}
return {h:~~(seconds / 3600),m:~~((seconds % 3600) / 60),s:~~seconds % 60}

}

(used Vishal's code)

Upvotes: 1

ggorlen
ggorlen

Reputation: 56965

Here's an ES6 version of the seconds to minutes and seconds conversion, with padding (00:00 format). It only accepts integer values for seconds and ~~(x) is the shorthand floor operation.

const padTime = n => ("" + n).padStart(2, 0);
const secondsToMinSec = time =>
  `${padTime(~~(time / 60))}:${padTime(time - ~~(time / 60) * 60)}`
;

for (let i = 0; i < 10; i++) {
  const seconds = ~~(Math.random() * 300);
  console.log(seconds, secondsToMinSec(seconds));
}

Upvotes: 1

Zombo
Zombo

Reputation: 1

I prefer thinking of Millisecond as its own unit, rather than as a subunit of something else. In that sense, it will have values of 0-999, so you're going to want to Pad three instead of two like I have seen with other answers. Here is an implementation:

function format(n) {
   let mil_s = String(n % 1000).padStart(3, '0');
   n = Math.trunc(n / 1000);
   let sec_s = String(n % 60).padStart(2, '0');
   n = Math.trunc(n / 60);
   return String(n) + ' m ' + sec_s + ' s ' + mil_s + ' ms';
}

console.log(format(241));

https://developer.mozilla.org/Web/JavaScript/Reference/Global_Objects/String/padStart

Upvotes: 1

Jakub Muda
Jakub Muda

Reputation: 6714

2020 UPDATE

Using basic math and simple javascript this can be done in just a few lines of code.

EXAMPLE - Convert 7735 seconds to HH:MM:SS.


MATH:

Calculations use:

  1. Math.floor() - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/floor

The Math.floor() function returns the largest integer less than or equal to a given number.

  1. % arithmetic operator (Remainder) - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators#Remainder

The remainder operator returns the remainder left over when one operand is divided by a second operand. It always takes the sign of the dividend.

Check out code below. Seconds are divided by 3600 to get number of hours and a remainder, which is used to calculate number of minutes and seconds.

HOURS => 7735 / 3600 = 2 remainder 535

MINUTES => 535 / 60 = 8 remainder 55

SECONDS => 55


LEADING ZEROS:

Many answers here use complicated methods to show number of hours, minutes and seconds in a proper way with leading zero - 45, 04 etc. This can be done using padStart(). This works for strings so the number must be converted to string using toString().

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/padStart

The padStart() method pads the current string with another string (multiple times, if needed) until the resulting string reaches the given length. The padding is applied from the start of the current string.


CODE:

function secondsToTime(e){
    const h = Math.floor(e / 3600).toString().padStart(2,'0'),
          m = Math.floor(e % 3600 / 60).toString().padStart(2,'0'),
          s = Math.floor(e % 60).toString().padStart(2,'0');
    
    return h + ':' + m + ':' + s;
    //return `${h}:${m}:${s}`;
}

console.log(secondsToTime(7735));  // 02:08:55

/*
secondsToTime(SECONDS) // HH:MM:SS 

secondsToTime(8)       // 00:00:08 
secondsToTime(68)      // 00:01:08
secondsToTime(1768)    // 00:29:28
secondsToTime(3600)    // 01:00:00
secondsToTime(5296)    // 01:28:16
secondsToTime(7735)    // 02:08:55
secondsToTime(45296)   // 12:34:56
secondsToTime(145296)  // 40:21:36
secondsToTime(1145296) // 318:08:16
*/

Upvotes: 67

DEV Tiago Fran&#231;a
DEV Tiago Fran&#231;a

Reputation: 1696

1 - Get rest of division using %. Now you have the seconds that don't complete a minute 2 - Subtract the seconds obtained in step 1 from the total. Now you have the minutes

For example, let's assume you have 700 seconds:

seconds = 700%60); //40 seconds
minutes = (700 - (700%60))/60; //11
//11:40

Upvotes: 2

Sushil
Sushil

Reputation: 2490

Try this:
Converting Second to HOURS, MIN and SEC.

function convertTime(sec) {
    var hours = Math.floor(sec/3600);
    (hours >= 1) ? sec = sec - (hours*3600) : hours = '00';
    var min = Math.floor(sec/60);
    (min >= 1) ? sec = sec - (min*60) : min = '00';
    (sec < 1) ? sec='00' : void 0;

    (min.toString().length == 1) ? min = '0'+min : void 0;    
    (sec.toString().length == 1) ? sec = '0'+sec : void 0;    
    
    return hours+':'+min+':'+sec;
}

Upvotes: 3

Nevyn
Nevyn

Reputation: 17

You've done enough code to track minutes and seconds portions of time.

What you could do is add the hours factor in:

var hrd = time % (60 * 60 * 60);
var hours = Math.floor(hrd / 60);

var mind = hrd % 60;
var minutes = Math.floor(mind / 60);

var secd = mind % 60;
var seconds = Math.ceil(secd);

var moreminutes = minutes + hours * 60

Upvotes: -1

Sebastian Scholl
Sebastian Scholl

Reputation: 1105

strftime.js (strftime github) is one of the best time formatting libraries. It's extremely light - 30KB - and effective. Using it you can convert seconds into time easily in one line of code, relying mostly on the native Date class.

When creating a new Date, each optional argument is positional as follows:

new Date(year, month, day, hours, minutes, seconds, milliseconds);

So if you initialize a new Date with all arguments as zero up to the seconds, you'll get:

var seconds = 150;
var date = new Date(0,0,0,0,0,seconds);
=> Sun Dec 31 1899 00:02:30 GMT-0500 (EST)

You can see that 150 seconds is 2-minutes and 30-seconds, as seen in the date created. Then using an strftime format ("%M:%S" for "MM:SS"), it will output your minutes' string.

var mm_ss_str = strftime("%M:%S", date);
=> "02:30"

In one line, it would look like:

var mm_ss_str = strftime('%M:%S', new Date(0,0,0,0,0,seconds));
=> "02:30"

Plus this would allow you to interchangeable support HH:MM:SS and MM:SS based on the number of seconds. For example:

# Less than an Hour (seconds < 3600)
var seconds = 2435;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "40:35"

# More than an Hour (seconds >= 3600)
var seconds = 10050;
strftime((seconds >= 3600 ? '%H:%M:%S' : '%M:%S'), new Date(0,0,0,0,0,seconds));
=> "02:47:30"

And of course, you can simply pass whatever format you want to strftime if you want the time string to be more or less semantic.

var format = 'Honey, you said you\'d be read in %S seconds %M minutes ago!';
strftime(format, new Date(0,0,0,0,0,1210));
=> "Honey, you said you'd be read in 10 seconds 20 minutes ago!"

Upvotes: -1

junho
junho

Reputation: 3841

Day.js

If you use day.js, try this.

const dayjs = require('dayjs')
const duration = require('dayjs/plugin/duration') 
dayjs.extend(duration)

const time = dayjs.duration(100, 'seconds')

time.seconds() // 40
time.minutes() // 1
time.format('mm:ss') // 01:40

Upvotes: 1

Sahil Chimnani
Sahil Chimnani

Reputation: 115

  function formatSeconds(s: number) {
    let minutes = ~~(s / 60);
    let seconds = ~~(s % 60);
    return minutes + ':' + seconds;
  }

Upvotes: 4

Diriector_Doc
Diriector_Doc

Reputation: 610

The most concise method I found can be done using in just one line:

let timeString = `${timeInSeconds/60|0}:${timeInSeconds%60}`

Explanation

`${...}`
Template literals. Allows for expressions to be converted into a string from within the string itself.
Note: Incompatible with IE.

timeInSeconds/60|0
Takes the seconds and converts in into minutes (/60). This gives a rational number. From here it is truncated using the bitwise OR (|0)

timeInSeconds%60
Remainder (modulo). Gives the remainder of the variable divided by 60.


Hours

This method can be expanded to include hours like this:

let timeString = `${timeInSeconds/60/60|0}:${timeInSeconds/60%60|0}:${timeInSeconds%60}`

Repeating this process, you can even include days.

Upvotes: 9

Gil Epshtain
Gil Epshtain

Reputation: 9801

Moment.js

If you are using Moment.js then you can use there built in Duration object

const duration = moment.duration(4825, 'seconds');

const h = duration.hours(); // 1
const m = duration.minutes(); // 20
const s = duration.seconds(); // 25

Upvotes: 14

Илья Зелень
Илья Зелень

Reputation: 8098

2019 best variant

Format hh:mm:ss

console.log(display(60 * 60 * 2.5 + 25)) // 2.5 hours + 25 seconds

function display (seconds) {
  const format = val => `0${Math.floor(val)}`.slice(-2)
  const hours = seconds / 3600
  const minutes = (seconds % 3600) / 60

  return [hours, minutes, seconds % 60].map(format).join(':')
}

Upvotes: 33

user2734839
user2734839

Reputation: 217

After all this, yet another simple solution:

const time = new Date(null);
time.setSeconds(7530);
console.log(time.getHours(), time.getMinutes(), time.getSeconds());

Upvotes: 5

Sam Logan
Sam Logan

Reputation: 3483

Clean one liner using ES6


const secondsToMinutes = seconds => Math.floor(seconds / 60) + ':' + ('0' + Math.floor(seconds % 60)).slice(-2);

Upvotes: 11

sivamani s
sivamani s

Reputation: 197

The Following function will help you to get Days , Hours , Minutes , seconds

toDDHHMMSS(inputSeconds){
        const Days = Math.floor( inputSeconds / (60 * 60 * 24) );
        const Hour = Math.floor((inputSeconds % (60 * 60 * 24)) / (60 * 60));
        const Minutes = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) / 60 );
        const Seconds = Math.floor(((inputSeconds % (60 * 60 * 24)) % (60 * 60)) % 60 );
        let ddhhmmss  = '';
        if (Days > 0){
            ddhhmmss += Days + ' Day ';
        }
        if (Hour > 0){
            ddhhmmss += Hour + ' Hour ';
        }

        if (Minutes > 0){
            ddhhmmss += Minutes + ' Minutes ';
        }

        if (Seconds > 0){
            ddhhmmss += Seconds + ' Seconds ';
        }
        return ddhhmmss;
    }
alert( toDDHHMMSS(2000));

Upvotes: 5

Anmol Devta
Anmol Devta

Reputation: 41

var seconds = 60;
var measuredTime = new Date(null);
measuredTime.setSeconds(seconds); // specify value of SECONDS
var Time = measuredTime.toISOString().substr(11, 8);
document.getElementById("id1").value = Time;
<div class="form-group">
  <label for="course" class="col-md-4">Time</label>
  <div class="col-md-8">
    <input type="text" class="form-control" id="id1" name="field">Min
  </div>
</div>

Upvotes: 2

Abdul Rehman
Abdul Rehman

Reputation: 47

export function TrainingTime(props) {
    const {train_time } = props;
    const hours = Math.floor(train_time/3600);
    const minutes = Math.floor((train_time-hours * 3600) / 60);
    const seconds = Math.floor((train_time%60));

    return `${hours} hrs  ${minutes} min  ${seconds} sec`;
}

Upvotes: 1

Ahmad Awais
Ahmad Awais

Reputation: 37120

Another but much more elegant solution for this is as follows:

/**
 * Convert number secs to display time
 *
 * 65 input becomes 01:05.
 *
 * @param Number inputSeconds Seconds input.
 */
export const toMMSS = inputSeconds => {
    const secs = parseInt( inputSeconds, 10 );
    let minutes = Math.floor( secs / 60 );
    let seconds = secs - minutes * 60;

    if ( 10 > minutes ) {
        minutes = '0' + minutes;
    }
    if ( 10 > seconds ) {
        seconds = '0' + seconds;
    }

    // Return display.
    return minutes + ':' + seconds;
};

Upvotes: 4

El0din
El0din

Reputation: 3370

function secondsToMinutes(time){
    return Math.floor(time / 60)+':'+Math.floor(time % 60);
}

Upvotes: 24

thatOneGuy
thatOneGuy

Reputation: 10622

Put my two cents in :

function convertSecondsToMinutesAndSeconds(seconds){
            var minutes;
            var seconds;
            minutes = Math.floor(seconds/60);
            seconds = seconds%60;

            return [minutes, seconds];
        }

So this :

var minutesAndSeconds = convertSecondsToMinutesAndSeconds(101);

Will have the following output :

[1,41];

Then you can print it like so :

console.log('TIME : ' +  minutesSeconds[0] + ' minutes, ' + minutesSeconds[1] + ' seconds');

//TIME : 1 minutes, 41 seconds

Upvotes: 1

dcb
dcb

Reputation: 79

A one liner (doesnt work with hours):

 function sectostr(time) {
    return ~~(time / 60) + ":" + (time % 60 < 10 ? "0" : "") + time % 60;
 }

Upvotes: 7

GitaarLAB
GitaarLAB

Reputation: 14645

For people dropping in hoping for a quick simple and thus short solution to format seconds into M:SS :

function fmtMSS(s){return(s-(s%=60))/60+(9<s?':':':0')+s}

done..
The function accepts either a Number (preferred) or a String (2 conversion 'penalties' which you can halve by prepending + in the function call's argument for s as in: fmtMSS(+strSeconds)), representing positive integer seconds s as argument.

Examples:

fmtMSS(    0 );  //   0:00
fmtMSS(   '8');  //   0:08
fmtMSS(    9 );  //   0:09
fmtMSS(  '10');  //   0:10
fmtMSS(   59 );  //   0:59
fmtMSS( +'60');  //   1:00
fmtMSS(   69 );  //   1:09
fmtMSS( 3599 );  //  59:59
fmtMSS('3600');  //  60:00
fmtMSS('3661');  //  61:01
fmtMSS( 7425 );  // 123:45

Breakdown:

function fmtMSS(s){   // accepts seconds as Number or String. Returns m:ss
  return( s -         // take value s and subtract (will try to convert String to Number)
          ( s %= 60 ) // the new value of s, now holding the remainder of s divided by 60 
                      // (will also try to convert String to Number)
        ) / 60 + (    // and divide the resulting Number by 60 
                      // (can never result in a fractional value = no need for rounding)
                      // to which we concatenate a String (converts the Number to String)
                      // who's reference is chosen by the conditional operator:
          9 < s       // if    seconds is larger than 9
          ? ':'       // then  we don't need to prepend a zero
          : ':0'      // else  we do need to prepend a zero
        ) + s ;       // and we add Number s to the string (converting it to String as well)
}

Note: Negative range could be added by prepending (0>s?(s=-s,'-'):'')+ to the return expression (actually, (0>s?(s=-s,'-'):0)+ would work as well).

Upvotes: 115

Related Questions