19

I am using javascript Date object trying to convert millisecond to how many hour, minute and second it is.

I have the currentTime in milliseconds

var currentTime = new Date().getTime()

and I have futureTime in milliseconds

var futureTime = '1432342800000'

I wanted to get difference in millisecond

var timeDiff = futureTime - currentTime

the the timeDiff was

timeDiff = '2568370873'

I want to know how many hours, minutes, seconds it is.

Could anyone help?

haeminish
  • 988
  • 5
  • 15
  • 29

10 Answers10

24
const secDiff = timeDiff / 1000; //in s
const minDiff = timeDiff / 60 / 1000; //in minutes
const hDiff = timeDiff / 3600 / 1000; //in hours  

updated

function msToHMS( ms ) {
    // 1- Convert to seconds:
    let seconds = ms / 1000;
    // 2- Extract hours:
    const hours = parseInt( seconds / 3600 ); // 3,600 seconds in 1 hour
    seconds = seconds % 3600; // seconds remaining after extracting hours
    // 3- Extract minutes:
    const minutes = parseInt( seconds / 60 ); // 60 seconds in 1 minute
    // 4- Keep only seconds not extracted to minutes:
    seconds = seconds % 60;
    alert( hours+":"+minutes+":"+seconds);
}

const timespan = 2568370873; 
msToHMS( timespan );  

Demo

Ronan Quillevere
  • 3,699
  • 1
  • 29
  • 44
ozil
  • 6,930
  • 9
  • 33
  • 56
14

If you are confident that the period will always be less than a day you could use this one-liner:

new Date(timeDiff).toISOString().slice(11,19)   // HH:MM:SS

N.B. This will be wrong if timeDiff is greater than a day.

tdbit
  • 933
  • 11
  • 15
9

Convert ms to hh:mm:ss

function millisecondsToHuman(ms) {
  const seconds = Math.floor((ms / 1000) % 60);
  const minutes = Math.floor((ms / 1000 / 60) % 60);
  const hours = Math.floor((ms  / 1000 / 3600 ) % 24)

  const humanized = [
    pad(hours.toString(), 2),
    pad(minutes.toString(), 2),
    pad(seconds.toString(), 2),
  ].join(':');

  return humanized;
}
=
Community
  • 1
  • 1
Mamunur Rashid
  • 1,095
  • 17
  • 28
  • 6
    Where `pad` is defined? I don't find it as a Javascript function. – Mark Apr 08 '22 at 08:45
  • pad function ``` function pad(numberString, size) { let padded = numberString; while (padded.length < size) { padded = `0${padded}`; } return padded; } ``` – masoud soroush Jan 29 '23 at 17:21
3
function msToHMS( duration ) {

     var milliseconds = parseInt((duration % 1000) / 100),
        seconds = parseInt((duration / 1000) % 60),
        minutes = parseInt((duration / (1000 * 60)) % 60),
        hours = parseInt((duration / (1000 * 60 * 60)) % 24);

      hours = (hours < 10) ? "0" + hours : hours;
      minutes = (minutes < 10) ? "0" + minutes : minutes;
      seconds = (seconds < 10) ? "0" + seconds : seconds;

      return hours + ":" + minutes + ":" + seconds ;
}
Palsri
  • 442
  • 4
  • 13
  • 1
    If you want to get more than 24 hours then edit this line: hours = parseInt((duration / (1000 * 60 * 60)));". Removing '% 24'. – lanmaster Oct 21 '20 at 06:21
3

Converts milliseconds to a string in the format hh:mm:ss. Here's my version:

function HHMMSSFromMilliseconds(ms) {
  // 1- Convert to seconds:
  var seconds = ms / 1000;

  // 2- Extract hours:
  var hours = parseInt(seconds / 3600); // 3600 seconds in 1 hour
  seconds = parseInt(seconds % 3600); // extract the remaining seconds after extracting hours

  // 3- Extract minutes:
  var minutes = parseInt(seconds / 60); // 60 seconds in 1 minute

  // 4- Keep only seconds not extracted to minutes:
  seconds = parseInt(seconds % 60);

  // 5 - Format so it shows a leading zero if needed
  let hoursStr = ("00" + hours).slice(-2);
  let minutesStr = ("00" + minutes).slice(-2);
  let secondsStr = ("00" + seconds).slice(-2);

  return hoursStr + ":" + minutesStr + ":" + secondsStr
}

let timespan = 23570 * 1000;
let formattedTime = HHMMSSFromMilliseconds(timespan);

console.log(formattedTime);
rky
  • 15
  • 3
titusmagnus
  • 2,014
  • 3
  • 23
  • 23
2

Convert millis to DD(days):HH:MM:SS

function formatTime(timeMS) {
    const [MS_IN_SEC, SEC_IN_DAY, SEC_IN_HOUR, SEC_IN_MIN] = [1000, 86400, 3600, 60];
    let seconds = Math.round(Math.abs(timeMS) / MS_IN_SEC);
    const days = Math.floor(seconds / SEC_IN_DAY);
    seconds = Math.floor(seconds % SEC_IN_DAY);
    const hours = Math.floor(seconds / SEC_IN_HOUR);
    seconds = Math.floor(seconds % SEC_IN_HOUR);
    const minutes = Math.floor(seconds / SEC_IN_MIN);
    seconds = Math.floor(seconds % SEC_IN_MIN);
    const [dd, hh, mm, ss] = [days, hours, minutes, seconds]
        .map(item => item < 10 ? '0' + item : item.toString());
    return dd + ':' + hh + ':' + mm + ':' + ss;
}

1

I use this code to convert, (I used as a base some of the codes already presented), I just made a modification so that the minutes 1-9 are presented as 4:00 instead of 04:00 (as in the youtube timer) and it supports more than 24h.

function convertDuration(milliseconds) {
  const seconds = Math.floor((milliseconds / 1000) % 60);
  const minutes = Math.floor((milliseconds / 1000 / 60) % 60);
  const hours = Math.floor((milliseconds / 1000 / 60 / 60));

  let formattedTime;

  if (milliseconds < 60000) {
    formattedTime = [minutes.toString().padStart(2, "0"), seconds.toString().padStart(2, "0")].join(":");
  } else {
    if (hours === 0) {
      formattedTime = [minutes.toString(), seconds.toString().padStart(2, "0")].join(":");
    } else {
      formattedTime = [hours.toString(), minutes.toString().padStart(2, "0"), seconds.toString().padStart(2, "0")].join(":");
    }
  }

  return formattedTime;
}

// Ex Outputs:
console.log(convertDuration(1000)); // Output: 00:01
console.log(convertDuration(10000)); // Output: 00:10
console.log(convertDuration(60000)); // Output: 1:00
console.log(convertDuration(600000)); // Output: 10:00
console.log(convertDuration(3723000)); // Output: 1:02:03
console.log(convertDuration(86400000)); // Output: 24:00:00
console.log(convertDuration(93720000)); // Output: 26:02:00
0

The difference in time is in milliseconds: Get time difference between two dates in seconds

to get the difference you have to use math.floor() http://www.w3schools.com/jsref/jsref_floor.asp

var secDiff = Math.floor(timeDiff / 1000); //in s
var minDiff = Math.floor(timeDiff / 60 / 1000); //in minutes
var hDiff = Math.floor(timeDiff / 3600 / 1000); //in hours
Community
  • 1
  • 1
Gijsbert Brouwer
  • 588
  • 5
  • 10
  • The secDiff gives the timeDiff all in seconds. I want the whole timeDiff to be converted to hh:mm:ss format. Not just converting timeDiff to be second OR minute OR hour. Is there any way to do this? – haeminish Apr 23 '15 at 07:54
  • As far as I know, you have to build up a new Date using the miliseconds known in the timediff. This new date object has the info you need. – Gijsbert Brouwer Apr 23 '15 at 08:15
  • @GijsbertBrouwer—Date objects are just a millisecond value (and a bunch of methods), so once you have the difference in milliseconds you have as much data as the Date. ;-) – RobG Oct 16 '17 at 23:47
0
var timediff = futureTime - currentTime
long seconds = (long) (timediff / 1000) % 60 ;
long minutes = (long) ((timediff / (1000*60)) % 60);
long hours   = (long) ((timediff / (1000*60*60)) % 24);
if(hours>0)
    time = hours+" hrs : "+minutes+" mins";
else if(minutes>0)
    time = minutes+" mins";
else if(seconds>0)
    time = seconds+" secs";
Piyush Srivastava
  • 357
  • 1
  • 4
  • 21
0

Here is a simple function

function simplifiedMilliseconds(milliseconds) {

  const totalSeconds = parseInt(Math.floor(milliseconds / 1000));
  const totalMinutes = parseInt(Math.floor(totalSeconds / 60));
  const totalHours = parseInt(Math.floor(totalMinutes / 60));
  const days = parseInt(Math.floor(totalHours / 24));

  const seconds = parseInt(totalSeconds % 60);
  const minutes = parseInt(totalMinutes % 60);
  const hours = parseInt(totalHours % 24);

  let time = '1s';
  if (days > 0) {
    time = `${days}d:${hours}h:${minutes}m:${seconds}s`;
  } else if (hours > 0) {
    time = `${hours}h:${minutes}m:${seconds}s`;
  } else if (minutes > 0) {
    time = `${minutes}m:${seconds}s`;
  } else if (seconds > 0) {
    time = `${seconds}s`;
  }
  return time;
}
Jay Dadhaniya
  • 171
  • 4
  • 15