Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert seconds to days, hours, minutes and seconds

Tags:

javascript

I have a Javascript timing event with an infinite loop with a stop button.

It will display numbers when start button is click.Now I want this numbers converted to something like 4 hours, 3 minutes , 50 seconds

var c = 0;
var t;
var timer_is_on = 0;

function timedCount() {
  document.getElementById('txt').value = c;
  c = c + 1;
  t = setTimeout(function() {
    timedCount()
  }, 1000);
}

function doTimer() {
  if (!timer_is_on) {
    timer_is_on = 1;
    timedCount();
  }
}

function stopCount() {
  clearTimeout(t);
  timer_is_on = 0;

}

$(".start").on("click", function() {
  //var start = $.now();
  //alert(start);
  //console.log(start);
  doTimer();
  $(".end").show();
  $(".hide_div").show();
});
$(".end").on("click", function() {
  stopCount();
});
.hide_div {
  display: none;
}

.end {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p class="start">Start</p>
<p class="end">End</p>
<p class="hide_div">
  <input type="text" id="txt" />//display numbers eg 12345
</p>

How to convert numbers like 123456 to 1 day, 4 hours, 40 min, 45 seconds?

like image 705
Danielle Rose Mabunga Avatar asked Mar 19 '16 07:03

Danielle Rose Mabunga


People also ask

How do you convert days seconds to hours minutes and seconds?

int seconds = (totalSeconds % 60); int minutes = (totalSeconds % 3600) / 60; int hours = (totalSeconds % 86400) / 3600; int days = (totalSeconds % (86400 * 30)) / 86400; First line - We get the remainder of seconds when dividing by number of seconds in a minutes.

How many hours and minutes and seconds in a day?

One day has 24 hours, one hour has 60 minutes and one minute has 60 seconds, so 24 hours/day times, 60 minutes/hour times, 60 seconds/minute is equal to 86400 seconds/day.

How long is a day exactly in seconds?

Similarly one day has been set to 86400 seconds exactly, rather than 23 hours 56 minutes 4.091 seconds which is the sidereal average.

How to calculate the number of seconds in a datetime?

from datetime import datetime, timedelta sec = timedelta (seconds= (int (input ('Enter the number of seconds: ')))) time = str (sec)

How many days in86400 seconds in a day?

86400 is the the total seconds in a day (60 seconds * 60 minutes * 24 hours). Dividing the inputted seconds by this value gives us number of days. We just need the whole part so we use Math.floor because the fractional piece is handled by this part:

How to calculate total seconds in a day using JavaScript?

86400 is the the total seconds in a day (60 seconds * 60 minutes * 24 hours). Dividing the inputted seconds by this value gives us number of days. We just need the whole part so we use Math.floor because the fractional piece is handled by this part: Convert seconds to HH-MM-SS with JavaScript? It just outputs hh:mm:ss, no days.


6 Answers

I suggest doing this way!:

function secondsToDhms(seconds) {
seconds = Number(seconds);
var d = Math.floor(seconds / (3600*24));
var h = Math.floor(seconds % (3600*24) / 3600);
var m = Math.floor(seconds % 3600 / 60);
var s = Math.floor(seconds % 60);

var dDisplay = d > 0 ? d + (d == 1 ? " day, " : " days, ") : "";
var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
return dDisplay + hDisplay + mDisplay + sDisplay;
}
like image 92
Andris Avatar answered Oct 17 '22 00:10

Andris


Use Math like this way, Second param in parseInt is for base, which is optional

var seconds = parseInt(123456, 10);

var days = Math.floor(seconds / (3600*24));
seconds  -= days*3600*24;
var hrs   = Math.floor(seconds / 3600);
seconds  -= hrs*3600;
var mnts = Math.floor(seconds / 60);
seconds  -= mnts*60;
console.log(days+" days, "+hrs+" Hrs, "+mnts+" Minutes, "+seconds+" Seconds");

Your given seconds 123456 would be 1 days, 10 Hrs, 17 Minutes, 36 Seconds not 1 days, 4 Hrs, 40 Minutes, 45 Seconds

like image 35
Niklesh Raut Avatar answered Oct 16 '22 23:10

Niklesh Raut


function countdown(s) {

  const d = Math.floor(s / (3600 * 24));

  s  -= d * 3600 * 24;

  const h = Math.floor(s / 3600);

  s  -= h * 3600;

  const m = Math.floor(s / 60);

  s  -= m * 60;

  const tmp = [];

  (d) && tmp.push(d + 'd');

  (d || h) && tmp.push(h + 'h');

  (d || h || m) && tmp.push(m + 'm');

  tmp.push(s + 's');

  return tmp.join(' ');
}

// countdown(3546544) -> 41d 1h 9m 4s
// countdown(436654) -> 5d 1h 17m 34s
// countdown(3601) -> 1h 0m 1s
// countdown(121) -> 2m 1s
like image 45
stopsopa Avatar answered Oct 16 '22 23:10

stopsopa


My solution with map() and reduce():

const intervalToLevels = (interval, levels) => {
  const cbFun = (d, c) => {
    let bb = d[1] % c[0],
      aa = (d[1] - bb) / c[0];
    aa = aa > 0 ? aa + c[1] : '';

    return [d[0] + aa, bb];
  };

  let rslt = levels.scale.map((d, i, a) => a.slice(i).reduce((d, c) => d * c))
    .map((d, i) => ([d, levels.units[i]]))
    .reduce(cbFun, ['', interval]);
  return rslt[0];
};

const TimeLevels = {
  scale: [24, 60, 60, 1],
  units: ['d ', 'h ', 'm ', 's ']
};
const secondsToString = interval => intervalToLevels(interval, TimeLevels);

If you call secondsToString(123456), you can get "1d 10h 17m 36s "

like image 38
timothyzhang Avatar answered Oct 17 '22 01:10

timothyzhang


Here is my solution, a simple function that will round to the nearest second!

var returnElapsedTime = function(epoch) {
  //We are assuming that the epoch is in seconds
  var hours = epoch / 3600,
      minutes = (hours % 1) * 60,
      seconds = (minutes % 1) * 60;
  return Math.floor(hours) + " hours, " + Math.floor(minutes) + " minutes, " + Math.round(seconds) + " seconds";
}
like image 42
Big Sam Avatar answered Oct 16 '22 23:10

Big Sam


Came up with my own variation to some of the solutions suggested in this thread.

if (!Number.prototype.secondsToDHM) {
    Number.prototype.secondsToDHM = function() {
        const secsPerDay = 86400;
        const secsPerHour = 3600;
        const secsPerMinute = 60;

        var seconds = Math.abs(this);
        var minus   = (this < 0) ? '-' : '';
        
        var days    = Math.floor(seconds / secsPerDay);
        seconds     = (seconds % secsPerDay);
        var hours   = Math.floor(seconds / secsPerHour);
        seconds     = (seconds % secsPerHour);
        var minutes = Math.floor(seconds / secsPerMinute);
        seconds     = (seconds % secsPerMinute);

        var sDays    = new String(days).padStart(1, '0');
        var sHours   = new String(hours).padStart(2, '0');
        var sMinutes = new String(minutes).padStart(2, '0');

        return `${minus}${sDays}D ${sHours}:${sMinutes}`;
    }
}

var a = new Number(50000).secondsToDHM();
var b = new Number(100000).secondsToDHM();
var c = new Number(200000).secondsToDHM();
var d = new Number(400000).secondsToDHM();

console.log(a);
console.log(b);
console.log(c);
console.log(d);
like image 29
Jay Avatar answered Oct 16 '22 23:10

Jay