Related
Hey I try to run the timer always until 24 o'clock but it always runs 24 when the page is loaded. I do not understand how I can calculate that the timer always shows the correct time until 24 o'clock can someone help me?
const countToDate = new Date().setHours(new Date().getHours() + 24)
let previousTimeBetweenDates
setInterval(() => {
const currentDate = new Date()
const timeBetweenDates = Math.ceil((countToDate - currentDate) / 1000)
flipAllCards(timeBetweenDates)
previousTimeBetweenDates = timeBetweenDates
}, 250)
function flipAllCards(time) {
const seconds = time % 60
const minutes = Math.floor(time / 60) % 60
const hours = Math.floor(time / 3600)
flip(document.querySelector("[data-hours-tens]"), Math.floor(hours / 10))
flip(document.querySelector("[data-hours-ones]"), hours % 10)
flip(document.querySelector("[data-minutes-tens]"), Math.floor(minutes / 10))
flip(document.querySelector("[data-minutes-ones]"), minutes % 10)
flip(document.querySelector("[data-seconds-tens]"), Math.floor(seconds / 10))
flip(document.querySelector("[data-seconds-ones]"), seconds % 10)
}
function flip(flipCard, newNumber) {
const topHalf = flipCard.querySelector(".top")
const startNumber = parseInt(topHalf.textContent)
if (newNumber === startNumber) return
const bottomHalf = flipCard.querySelector(".bottom")
const topFlip = document.createElement("div")
topFlip.classList.add("top-flip")
const bottomFlip = document.createElement("div")
bottomFlip.classList.add("bottom-flip")
top.textContent = startNumber
bottomHalf.textContent = startNumber
topFlip.textContent = startNumber
bottomFlip.textContent = newNumber
topFlip.addEventListener("animationstart", e => {
topHalf.textContent = newNumber
})
topFlip.addEventListener("animationend", e => {
topFlip.remove()
})
bottomFlip.addEventListener("animationend", e => {
bottomHalf.textContent = newNumber
bottomFlip.remove()
})
flipCard.append(topFlip, bottomFlip)
}
I have to convert seconds to time format:
seconds_1 = 540;
seconds_2 = -2820;
convert_1 = new Date(seconds_1 * 1000).toISOString().substr(11, 8);
convert_2 = new Date(seconds_2 * 1000).toISOString().substr(11, 8);
console.log(convert_1);
console.log(convert_2);
it will return,
convert_1 : 00:09:00
convert_2 : 23:13:00
first one (convert_1) is correct, but the second one should return -00:47:00 .
The Actual issue is, the negative value is not converting to time correctly.
Please help.
I tried this,
function toTime(duration) {
// Hours, minutes and seconds
var hrs = ~~(duration / 3600);
var mins = ~~((duration % 3600) / 60);
var secs = ~~duration % 60;
let ret = hrs+ ":" + mins + ":" + secs;
return ret;
}
seconds_1 = 540;
seconds_2 = -2820;
console.log(toTime(seconds_2 ));
A pragmatic solution is to remove the sign and then add it again:
function toTime(seconds) {
if (seconds < 0) return "-" + toTime(-seconds);
return new Date(seconds * 1000).toISOString().substr(11, 8);
}
console.log(toTime(540));
console.log(toTime(-2820));
Just test
const convert = secs => {
const sign = secs < 0
const hhmmss = new Date(Math.abs(secs) * 1000).toISOString().substr(11, 8);
return sign ? '-' + hhmmss : hhmmss
}
console.log(convert(540));
console.log(convert(-2820));
I know there are easier ways to make a countdown Timer, but I need to do it with these three functions.
I tried returning the values of the getRemainingTime function as an Array, but got the same result.
The timer says undefined Tage undefined:undefined:undefined
const ReleaseDate = new Date("April 01, 2020 12:00:00").getTime();
//Calculate Days,Hours,Minutes,Seconds left
function getRemainingTime(CurrentDate, ReleaseDate){
const Differenz = ReleaseDate - CurrentDate;
const d= Math.floor(Differenz / (1000*60*60*24));
const h= Math.floor((Differenz / (1000*60*60*24)) / (1000*60*60));
const m= Math.floor((Differenz / (1000*60*60)) / (1000*60));
const s= Math.floor((Differenz / (1000*60)) / 1000);
//return multiple values as objects
return {d:d, h:h, m:m, s:s};
}
//produce and return strings
function formatDays(days){
return (days + " Tage ");
}
function formatTime(hours, minutes, seconds){
return (hours + ":" + minutes + ":" + seconds);
}
function updateCountdown(){
//repeat every second
const TimerFunction = setInterval(function(){
//calculate time now
const CurrentDate = new Date().getTime();
//call function to calculate days,hours,minutes,seconds
getRemainingTime();
//access Objects
const values = getRemainingTime();
const days = values.d;
const hours = values.h;
const minutes = values.m;
const seconds = values.s;
//call functions to produce strings
formatDays();
formatTime();
document.getElementById("Countdown-Timer").innerText = formatDays() + formatTime();
},1000)
}
//start updateCountdown function
updateCountdown();
const ReleaseDate = new Date("April 01, 2020 12:00:00").getTime();
function getRemainingTime(CurrentDate, ReleaseDate) {
const Differenz = ReleaseDate - CurrentDate;
const d = Math.floor(Differenz / (1000 * 60 * 60 * 24));
const h = Math.floor((Differenz / (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
const m = Math.floor((Differenz / (1000 * 60 * 60)) / (1000 * 60));
const s = Math.floor((Differenz / (1000 * 60)) / 1000);
return {
d: d,
h: h,
m: m,
s: s
};
}
function formatDays(days) {
return (days + " Tage ");
}
function formatTime(hours, minutes, seconds) {
return (hours + ":" + minutes + ":" + seconds);
}
function updateCountdown() {
const TimerFunction = setInterval(function () {
const CurrentDate = new Date().getTime();
getRemainingTime(CurrentDate, ReleaseDate);
const values = getRemainingTime(CurrentDate, ReleaseDate);
const days = values.d;
const hours = values.h;
const minutes = values.m;
const seconds = values.s;
formatDays(days);
formatTime(hours, minutes, seconds);
document.getElementById("Countdown-Timer").innerText = (formatDays(days) + formatTime(hours, minutes, seconds));
}, 1000)
}
updateCountdown();
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?
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;
}
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
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
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 "
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";
}
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);
This answer builds upon on Andris' approach to this question, but it doesn't have trailing commas if lesser units are not present.
It also borrows from this answer dealing with joining array values only if truthy:
https://stackoverflow.com/a/19903063
I'm not a javascript god and it's probably horribly over-engineered, but hopefully readable and correct!
function sformat(s) {
// create array of day, hour, minute and second values
var fm = [
Math.floor(s / (3600 * 24)),
Math.floor(s % (3600 * 24) / 3600),
Math.floor(s % 3600 / 60),
Math.floor(s % 60)
];
// map over array
return $.map(fm, function(v, i) {
// if a truthy value
if (Boolean(v)) {
// add the relevant value suffix
if (i === 0) {
v = plural(v, "day");
} else if (i === 1) {
v = plural(v, "hour");
} else if (i === 2) {
v = plural(v, "minute");
} else if (i === 3) {
v = plural(v, "second");
}
return v;
}
}).join(', ');
}
function plural(value, unit) {
if (value === 1) {
return value + " " + unit;
} else if (value > 1) {
return value + " " + unit + "s";
}
}
console.log(sformat(60)); // 1 minute
console.log(sformat(3600)); // 1 hour
console.log(sformat(86400)); // 1 day
console.log(sformat(8991)); // 2 hours, 29 minutes, 51 seconds
If you needed to convey the duration more 'casually' in words, you could also do something like:
var remaining_duration = sformat(117);
// if a value is returned, add some prefix and suffix
if (remaining_duration !== "") {
remaining_duration = "about " + remaining_duration + " left";
}
$(".remaining_duration").text(remaining_duration);
// returns 'about 1 minute, 57 seconds left'
I further tweaked the code by Svetoslav as follows:
function convertSecondsToReadableString(seconds) {
seconds = seconds || 0;
seconds = Number(seconds);
seconds = Math.abs(seconds);
const d = Math.floor(seconds / (3600 * 24));
const h = Math.floor(seconds % (3600 * 24) / 3600);
const m = Math.floor(seconds % 3600 / 60);
const s = Math.floor(seconds % 60);
const parts = [];
if (d > 0) {
parts.push(d + ' day' + (d > 1 ? 's' : ''));
}
if (h > 0) {
parts.push(h + ' hour' + (h > 1 ? 's' : ''));
}
if (m > 0) {
parts.push(m + ' minute' + (m > 1 ? 's' : ''));
}
if (s > 0) {
parts.push(s + ' second' + (s > 1 ? 's' : ''));
}
return parts.join(', ');
}
Short answer:
var s = (Math.floor(123456/86400) + ":" + (new Date(123456 * 1000)).toISOString().substr(11, 8)).split(":");
console.log(`${s[0]} days, ${s[1]} hours, ${s[2]} minutes, ${s[3]} seconds` )
Edit:
Let me break it down in parts :
Math.floor(123456/86400)
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:
(new Date(123456 * 1000)).toISOString().substr(11, 8)
the explanation can be found here:
Convert seconds to HH-MM-SS with JavaScript?
It just outputs hh:mm:ss, no days. So the first part and this part is a perfect combination
We concatenate using a colon (:) as a separator. The string looks like this:
'1:10:17:36'
We split it into an array with .split(":");. Then finally, we format the elements of the array for the desired output.
I've tweaked the code that Andris posted https://stackoverflow.com/users/3564943/andris
// https://stackoverflow.com/questions/36098913/convert-seconds-to-days-hours-minutes-and-seconds
function app_ste_36098913_countdown_seconds_to_hr(seconds) {
seconds = seconds || 0;
seconds = Number(seconds);
seconds = Math.abs(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 parts = new Array();
if (d > 0) {
var dDisplay = d > 0 ? d + ' ' + (d == 1 ? "day" : "days") : "";
parts.push(dDisplay);
}
if (h > 0) {
var hDisplay = h > 0 ? h + ' ' + (h == 1 ? "hour" : "hours") : "";
parts.push(hDisplay)
}
if (m > 0) {
var mDisplay = m > 0 ? m + ' ' + (m == 1 ? "minute" : "minutes") : "";
parts.push(mDisplay)
}
if (s > 0) {
var sDisplay = s > 0 ? s + ' ' + (s == 1 ? "second" : "seconds") : "";
parts.push(sDisplay)
}
return parts.join(', ', parts);
}
You will probably find using epoch timestamps more straightforward: As detailed in Convert a Unix timestamp to time in JavaScript, the basic method is like so:
<script>
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date1 = new Date();
alert ('easy trick to waste a few seconds...' + date1);
// var date = date2 - date1;
// Hours part from the timestamp
var hours1 = date1.getHours();
// Minutes part from the timestamp
var minutes1 = "0" + date1.getMinutes();
// Seconds part from the timestamp
var seconds1 = "0" + date1.getSeconds();
var date2 = new Date();
// Hours part from the timestamp
var hours2 = date2.getHours();
// Minutes part from the timestamp
var minutes2 = "0" + date2.getMinutes();
// Seconds part from the timestamp
var seconds2 = "0" + date2.getSeconds();
// Will display time in 10:30:23 format
// var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
var elapsedHrs = hours2 - hours1;
var elapsedMin = minutes2.substr(-2) -minutes1.substr(-2);
var elapsedSec = seconds2.substr(-2) - seconds1.substr(-2);
var elapsedTime = elapsedHrs + ' hours, ' + elapsedMin + ' minutes, ' + elapsedSec + ' seconds';
alert ('time between timestamps: ' + elapsedTime);
</script>
Be warned that this script needs some work since for now it will give negative values for things like date1 = 12:00:00 and date2 = 12:00:05, but I'll leave that to you fo now.
You should rewrite your code to take a timestamp ( var x = new Date(); ) at the start of your timer and one whenever you are done/want to check elapsed time, and subtract the two before parsing out elapsed seconds, minutes, hours etc as required.
This is my take at the question, even if it is an old topic.
You can use a loop to compute everything for you :
function time_remaining(date1, date2) {
let seconds = (date2 - date1) / 1000
let units = ["years", "days", "h", "min", "s"]
let limit_units = [365, 24, 60, 60, 1]
const reducer = (accumulator, curr) => accumulator * curr;
let time = []
for (let i = 0; i < units.length; i++) {
let divisor = limit_units.slice(i).reduce(reducer)
let value = Math.floor(seconds / divisor)
seconds = seconds - value * divisor
time.push(value)
}
return clean_time(time, units)
}
// at this point, you have your answer. However,
// we can improve the result by removing all none
// significative null units (i.e, if your countdown is
// only about hours, minutes and seconds, it is not
// going to include years and days.)
function clean_time(time, units) {
time = time.reverse()
while (time[time.length - 1] == 0) {
time.pop()
}
return [time.reverse(), units.slice(-time.length)]
}
let date1 = Date.parse("2023-07-09T17:50:33")
console.log(time_remaining(Date.now(), date1))
I have a time as a number of milliseconds and I want to convert it to a HH:MM:SS format. It should wrap around, with milliseconds = 86400000 I want to get 00:00:00.
How about creating a function like this:
function msToTime(duration) {
var milliseconds = Math.floor((duration % 1000) / 100),
seconds = Math.floor((duration / 1000) % 60),
minutes = Math.floor((duration / (1000 * 60)) % 60),
hours = Math.floor((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 + "." + milliseconds;
}
console.log(msToTime(300000))
To Convert time in millisecond to human readable format.
function msToTime(ms) {
let seconds = (ms / 1000).toFixed(1);
let minutes = (ms / (1000 * 60)).toFixed(1);
let hours = (ms / (1000 * 60 * 60)).toFixed(1);
let days = (ms / (1000 * 60 * 60 * 24)).toFixed(1);
if (seconds < 60) return seconds + " Sec";
else if (minutes < 60) return minutes + " Min";
else if (hours < 24) return hours + " Hrs";
else return days + " Days"
}
console.log(msToTime(1000))
console.log(msToTime(10000))
console.log(msToTime(300000))
console.log(msToTime(3600000))
console.log(msToTime(86400000))
I had the same problem, this is what I ended up doing:
function parseMillisecondsIntoReadableTime(milliseconds){
//Get hours from milliseconds
var hours = milliseconds / (1000*60*60);
var absoluteHours = Math.floor(hours);
var h = absoluteHours > 9 ? absoluteHours : '0' + absoluteHours;
//Get remainder from hours and convert to minutes
var minutes = (hours - absoluteHours) * 60;
var absoluteMinutes = Math.floor(minutes);
var m = absoluteMinutes > 9 ? absoluteMinutes : '0' + absoluteMinutes;
//Get remainder from minutes and convert to seconds
var seconds = (minutes - absoluteMinutes) * 60;
var absoluteSeconds = Math.floor(seconds);
var s = absoluteSeconds > 9 ? absoluteSeconds : '0' + absoluteSeconds;
return h + ':' + m + ':' + s;
}
var time = parseMillisecondsIntoReadableTime(86400000);
alert(time);
Here is my solution
let h,m,s;
h = Math.floor(timeInMiliseconds/1000/60/60);
m = Math.floor((timeInMiliseconds/1000/60/60 - h)*60);
s = Math.floor(((timeInMiliseconds/1000/60/60 - h)*60 - m)*60);
// to get time format 00:00:00
s < 10 ? s = `0${s}`: s = `${s}`
m < 10 ? m = `0${m}`: m = `${m}`
h < 10 ? h = `0${h}`: h = `${h}`
console.log(`${s}:${m}:${h}`);
This one returns time like youtube videos
function getYoutubeLikeToDisplay(millisec) {
var seconds = (millisec / 1000).toFixed(0);
var minutes = Math.floor(seconds / 60);
var hours = "";
if (minutes > 59) {
hours = Math.floor(minutes / 60);
hours = (hours >= 10) ? hours : "0" + hours;
minutes = minutes - (hours * 60);
minutes = (minutes >= 10) ? minutes : "0" + minutes;
}
seconds = Math.floor(seconds % 60);
seconds = (seconds >= 10) ? seconds : "0" + seconds;
if (hours != "") {
return hours + ":" + minutes + ":" + seconds;
}
return minutes + ":" + seconds;
}
Output:
getYoutubeLikeToDisplay(129900) = "2:10"
getYoutubeLikeToDisplay(1229900) = "20:30"
getYoutubeLikeToDisplay(21229900) = "05:53:50"
Sorry, late to the party. The accepted answer did not cut it for me, so I wrote it myself.
Output:
2h 59s
1h 59m
1h
1h 59s
59m 59s
59s
Code (Typescript):
function timeConversion(duration: number) {
const portions: string[] = [];
const msInHour = 1000 * 60 * 60;
const hours = Math.trunc(duration / msInHour);
if (hours > 0) {
portions.push(hours + 'h');
duration = duration - (hours * msInHour);
}
const msInMinute = 1000 * 60;
const minutes = Math.trunc(duration / msInMinute);
if (minutes > 0) {
portions.push(minutes + 'm');
duration = duration - (minutes * msInMinute);
}
const seconds = Math.trunc(duration / 1000);
if (seconds > 0) {
portions.push(seconds + 's');
}
return portions.join(' ');
}
console.log(timeConversion((60 * 60 * 1000) + (59 * 60 * 1000) + (59 * 1000)));
console.log(timeConversion((60 * 60 * 1000) + (59 * 60 * 1000) ));
console.log(timeConversion((60 * 60 * 1000) ));
console.log(timeConversion((60 * 60 * 1000) + (59 * 1000)));
console.log(timeConversion( (59 * 60 * 1000) + (59 * 1000)));
console.log(timeConversion( (59 * 1000)));
The above snippets don't work for cases with more than 1 day (They are simply ignored).
For this you can use:
function convertMS(ms) {
var d, h, m, s;
s = Math.floor(ms / 1000);
m = Math.floor(s / 60);
s = s % 60;
h = Math.floor(m / 60);
m = m % 60;
d = Math.floor(h / 24);
h = h % 24;
h += d * 24;
return h + ':' + m + ':' + s;
}
Thanks to https://gist.github.com/remino/1563878
I needed time only up to one day, 24h, this was my take:
const milliseconds = 5680000;
const hours = `0${new Date(milliseconds).getHours() - 1}`.slice(-2);
const minutes = `0${new Date(milliseconds).getMinutes()}`.slice(-2);
const seconds = `0${new Date(milliseconds).getSeconds()}`.slice(-2);
const time = `${hours}:${minutes}:${seconds}`
console.log(time);
you could get days this way as well if needed.
Format as hh:mm:ss with optional padding
(1:59:59 or 01:59:59)
(1:59 or 01:59)
(Default: no padding)
Based loosely on Chand's answer.
function formatMilliseconds(milliseconds, padStart) {
function pad(num) {
return `${num}`.padStart(2, '0');
}
let asSeconds = milliseconds / 1000;
let hours = undefined;
let minutes = Math.floor(asSeconds / 60);
let seconds = Math.floor(asSeconds % 60);
if (minutes > 59) {
hours = Math.floor(minutes / 60);
minutes %= 60;
}
return hours
? `${padStart ? pad(hours) : hours}:${pad(minutes)}:${pad(seconds)}`
: `${padStart ? pad(minutes) : minutes}:${pad(seconds)}`;
}
Tests:
let s = 1000;
let m = 60*s;
let h = 60*m;
console.log(formatMilliseconds(1*h)); // 1:00:00
console.log(formatMilliseconds(1*h, true)); // 01:00:00
console.log(formatMilliseconds(59*m + 59*s)); // 59:59
console.log(formatMilliseconds(59*m + 59*s, true)); // 59:59
console.log(formatMilliseconds(9*m + 9*s)); // 9:09
console.log(formatMilliseconds(9*m + 9*s, true)); // 09:09
console.log(formatMilliseconds(5*s)); // 0:05
console.log(formatMilliseconds(5*s, true)); // 00:05
console.log(formatMilliseconds(2400*s)); // 40:00
console.log(formatMilliseconds(2400*s, true)); // 40:00
.
.
.
If you need millisecond precision, you can get the fractional part using the following:
(asSeconds % 1).toFixed(3).substring(1)
Your returns would end up looking like this (break it up for readability as necessary):
`${padStart ? pad(hours) : hours}:${pad(minutes)}:${pad(seconds)}${(asSeconds % 1).toFixed(3).substring(1)}`
There are probably better ways to do that, but this naive solution gets the job done.
Test:
let asSeconds = 59.5219;
let seconds = Math.floor(asSeconds);
console.log(`${pad(seconds)}${(asSeconds % 1).toFixed(3).substring(1)}`);
// Equivalent to above, without using `pad()`:
//console.log(`${String(seconds).padStart(2, '0')}${(asSeconds % 1).toFixed(3).substring(1)}`);
// Output: 59.522
// The following is written in Typescript, should be easy to translate to JS
function humanReadableDuration(msDuration: int): string {
const h = Math.floor(msDuration / 1000 / 60 / 60);
const m = Math.floor((msDuration / 1000 / 60 / 60 - h) * 60);
const s = Math.floor(((msDuration / 1000 / 60 / 60 - h) * 60 - m) * 60);
// To get time format 00:00:00
const seconds: string = s < 10 ? `0${s}` : `${s}`;
const minutes: string = m < 10 ? `0${m}` : `${m}`;
const hours: string = h < 10 ? `0${h}` : `${h}`;
return `${hours}h ${minutes}m ${seconds}s`;
}
This solution uses one function to split milliseconds into a parts object, and another function to format the parts object.
I created 2 format functions, one as you requested, and another that prints a friendly string and considering singular/plural, and includes an option to show milliseconds.
function parseDuration(duration) {
let remain = duration
let days = Math.floor(remain / (1000 * 60 * 60 * 24))
remain = remain % (1000 * 60 * 60 * 24)
let hours = Math.floor(remain / (1000 * 60 * 60))
remain = remain % (1000 * 60 * 60)
let minutes = Math.floor(remain / (1000 * 60))
remain = remain % (1000 * 60)
let seconds = Math.floor(remain / (1000))
remain = remain % (1000)
let milliseconds = remain
return {
days,
hours,
minutes,
seconds,
milliseconds
};
}
function formatTime(o, useMilli = false) {
let parts = []
if (o.days) {
let ret = o.days + ' day'
if (o.days !== 1) {
ret += 's'
}
parts.push(ret)
}
if (o.hours) {
let ret = o.hours + ' hour'
if (o.hours !== 1) {
ret += 's'
}
parts.push(ret)
}
if (o.minutes) {
let ret = o.minutes + ' minute'
if (o.minutes !== 1) {
ret += 's'
}
parts.push(ret)
}
if (o.seconds) {
let ret = o.seconds + ' second'
if (o.seconds !== 1) {
ret += 's'
}
parts.push(ret)
}
if (useMilli && o.milliseconds) {
let ret = o.milliseconds + ' millisecond'
if (o.milliseconds !== 1) {
ret += 's'
}
parts.push(ret)
}
if (parts.length === 0) {
return 'instantly'
} else {
return parts.join(' ')
}
}
function formatTimeHMS(o) {
let hours = o.hours.toString()
if (hours.length === 1) hours = '0' + hours
let minutes = o.minutes.toString()
if (minutes.length === 1) minutes = '0' + minutes
let seconds = o.seconds.toString()
if (seconds.length === 1) seconds = '0' + seconds
return hours + ":" + minutes + ":" + seconds
}
function formatDurationHMS(duration) {
let time = parseDuration(duration)
return formatTimeHMS(time)
}
function formatDuration(duration, useMilli = false) {
let time = parseDuration(duration)
return formatTime(time, useMilli)
}
console.log(formatDurationHMS(57742343234))
console.log(formatDuration(57742343234))
console.log(formatDuration(5423401000))
console.log(formatDuration(500))
console.log(formatDuration(500, true))
console.log(formatDuration(1000 * 30))
console.log(formatDuration(1000 * 60 * 30))
console.log(formatDuration(1000 * 60 * 60 * 12))
console.log(formatDuration(1000 * 60 * 60 * 1))
Worked for me
msToTime(milliseconds) {
//Get hours from milliseconds
var hours = milliseconds / (1000*60*60);
var absoluteHours = Math.floor(hours);
var h = absoluteHours > 9 ? absoluteHours : '0' + absoluteHours;
//Get remainder from hours and convert to minutes
var minutes = (hours - absoluteHours) * 60;
var absoluteMinutes = Math.floor(minutes);
var m = absoluteMinutes > 9 ? absoluteMinutes : '0' + absoluteMinutes;
//Get remainder from minutes and convert to seconds
var seconds = (minutes - absoluteMinutes) * 60;
var absoluteSeconds = Math.floor(seconds);
var s = absoluteSeconds > 9 ? absoluteSeconds : '0' + absoluteSeconds;
return h == "00" ? m + ':' + s : h + ':' + m + ':' + s;
}
Human-readable code for human-readable output and you can extend this to light years or nanoseconds or what have you very intuitively. Obviously you'd want to convert this to a function and re-use some of those intermediate modulo calls.
second = 1000
minute = second * 60
hour = minute * 60
day = hour * 24
test = 3 * day + 2 * hour + 11 * minute + 58 * second
console.log(Math.floor(test / day))
console.log(Math.floor(test % day / hour))
console.log(Math.floor(test % day % hour / minute))
console.log(Math.floor(test % day % hour % minute / second))
Extending on #Rick's answer, I prefer something like this:
function msToReadableTime(time){
const second = 1000;
const minute = second * 60;
const hour = minute * 60;
let hours = Math.floor(time / hour % 24);
let minutes = Math.floor(time / minute % 60);
let seconds = Math.floor(time / second % 60);
return hours + ':' + minutes + ":" + seconds;
}
Based on #Chand answer. This is the implementation in Typescript. A bit safer than coercing types in JS. If you remove the type annotation should be valid JS. Also using new string functions to normalise the time.
function displayTime(millisec: number) {
const normalizeTime = (time: string): string => (time.length === 1) ? time.padStart(2, '0') : time;
let seconds: string = (millisec / 1000).toFixed(0);
let minutes: string = Math.floor(parseInt(seconds) / 60).toString();
let hours: string = '';
if (parseInt(minutes) > 59) {
hours = normalizeTime(Math.floor(parseInt(minutes) / 60).toString());
minutes = normalizeTime((parseInt(minutes) - (parseInt(hours) * 60)).toString());
}
seconds = normalizeTime(Math.floor(parseInt(seconds) % 60).toString());
if (hours !== '') {
return `${hours}:${minutes}:${seconds}`;
}
return `${minutes}:${seconds}`;
}
I recently ran into this situation. My focus was on clean readability and reusability.
Use
(See function definition below)
timeUnits(86400000) // {days: 1, hours: 0, minutes: 0, seconds: 0, ms: 0}
Then you can use the data to do whatever you want (like build a string).
Other examples:
timeUnits(214870123) // {days: 2, hours: 11, minutes: 41, seconds: 10, ms: 123}
timeUnits('70123') // null
Function
/**
* Converts milliseconds into greater time units as possible
* #param {int} ms - Amount of time measured in milliseconds
* #return {?Object} Reallocated time units. NULL on failure.
*/
function timeUnits( ms ) {
if ( !Number.isInteger(ms) ) {
return null
}
/**
* Takes as many whole units from the time pool (ms) as possible
* #param {int} msUnit - Size of a single unit in milliseconds
* #return {int} Number of units taken from the time pool
*/
const allocate = msUnit => {
const units = Math.trunc(ms / msUnit)
ms -= units * msUnit
return units
}
// Property order is important here.
// These arguments are the respective units in ms.
return {
// weeks: allocate(604800000), // Uncomment for weeks
days: allocate(86400000),
hours: allocate(3600000),
minutes: allocate(60000),
seconds: allocate(1000),
ms: ms // remainder
}
}
It's written in such a way so that you can easily implement other units (for example, where I commented out implementation for weeks) so long as you know their worth in milliseconds.
my solution
var sunriseMills = 1517573074000; // sunrise in NewYork on Feb 3, 2018 - UTC time
var offsetCityMills = -5 * 3600 * 1000; // NewYork delay to UTC
var offsetDeviceMills = new Date().getTimezoneOffset() * 60 * 1000 ; // eg. I live in Romania (UTC+2) >> getTimezoneOffset() = 120
var textTime = new Date(sunriseMills + offsetCityMills + offsetDeviceMills)
.toLocaleTimeString('en-US', { hour: 'numeric', minute: 'numeric' });
textTime will become '7.04 AM'
A Date object can be constructed from milliseconds:
const date = new Date(0, 0, 0, 0, 0, 0, milliseconds);
In your question you say milliseconds seconds should 'wrap around' at 86400000. Since we know there are 86400000 milliseconds in a day, we can simply take the time from the date object, and ignore every other part of the date as irrelevant.
The time can then be obtained in any number of formats. The one you require matches that used in the United Kingdom, locale en-GB:
const hms = d.toLocaleTimeString('en-GB');
If you're using typescript, this could be a good thing for you
enum ETime {
Seconds = 1000,
Minutes = 60000,
Hours = 3600000,
SecInMin = 60,
MinInHours = 60,
HoursMod = 24,
timeMin = 10,
}
interface ITime {
millis: number
modulo: number
}
const Times = {
seconds: {
millis: ETime.Seconds,
modulo: ETime.SecInMin,
},
minutes: {
millis: ETime.Minutes,
modulo: ETime.MinInHours,
},
hours: {
millis: ETime.Hours,
modulo: ETime.HoursMod,
},
}
const dots: string = ":"
const msToTime = (duration: number, needHours: boolean = true): string => {
const getCorrectTime = (divider: ITime): string => {
const timeStr: number = Math.floor(
(duration / divider.millis) % divider.modulo,
)
return timeStr < ETime.timeMin ? "0" + timeStr : String(timeStr)
}
return (
(needHours ? getCorrectTime(Times.hours) + dots : "") +
getCorrectTime(Times.minutes) +
dots +
getCorrectTime(Times.seconds)
)
}
In my implementation I used Moment.js:
export default (value) =>
const duration = moment.duration(value);
const milliseconds = duration.milliseconds();
const seconds = duration.seconds();
const minutes = duration.minutes();
const hours = duration.hours();
const day = duration.days();
const sDay = `${day}d `;
const sHours = (hours < 10) ? `0${hours}h ` : `${hours}h `;
const sMinutes = (minutes < 10) ? `0${minutes}' ` : `${minutes}' `;
const sSeconds = (seconds < 10) ? `0${seconds}" ` : `${seconds}" `;
const sMilliseconds = `${milliseconds}ms`;
...
}
Once got the strings, I composed them as I want.
I works for me as i get milliseconds=1592380675409 using javascript method getTime() which returns the number of milliseconds between midnight of January 1, 1970 and the specified date.
var d = new Date();//Wed Jun 17 2020 13:27:55 GMT+0530 (India Standard Time)
var n = d.getTime();//1592380675409 this value is store somewhere
//function call
console.log(convertMillisecToHrMinSec(1592380675409));
var convertMillisecToHrMinSec = (time) => {
let date = new Date(time);
let hr = date.getHours();
let min = date.getMinutes();
let sec = date.getSeconds();
hr = (hr < 10) ? "0"+ hr : hr;
min = (min < 10) ? "0"+ min : min;
sec = (sec < 10) ? "0"+ sec : sec;
return hr + ':' + min + ":" + sec;//01:27:55
}
A refactor from #dusht to ES6+ and more functional:
const addPrefix = time => time < 10 ? '0' + time : time;
const toHours = time => addPrefix(Math.floor((time / (1000 * 60 * 60)) % 24));
const toMinutes = time => addPrefix(Math.floor((time / (1000 * 60)) % 60));
const toSeconds = (ime => addPrefix(Math.floor((time / 1000) % 60));
const toMiliseconds = time => Math.floor((time % 1000) / 100);
const milisecondToHoursAndMinute = time => {
const hours = toHours(time);
const minutes = toMinutes(time);
const seconds = toSeconds(time);
const miliseconds = toMiliseconds(time);
return `${hours}:${minutes}:${seconds}.${miliseconds}`
}
let dateTimeStr = new Date(1949778000);
dateTimeStr = Math.floor(dateTimeStr/86400000) +' days '+ dateTimeStr.getHours() +' hours '+ dateTimeStr.getMinutes() +' minutes '+ dateTimeStr.getSeconds() +' seconds';
console.log(dateTimeStr);
You don't have to calculate the days if you don't need them
"22 days 16 hours 36 minutes 18 seconds"
I don't see the need for complication in all these answers, it's easy to add zeros by adding a power of 10:
function timeToString(t) {
const value =
((t / 3600_000 % 24) | 0) * 10000 +
((t / 60_000 % 60) | 0) * 100 +
((t / 1_000 % 60) | 0);
return (1000000 + value).toString().replace(/1(..)(..)(..)/, '$1:$2:$3');
}
If anyone still need here's a modified version of one of the code snippets posted above in js by https://stackoverflow.com/a/58826445/20067539
function timeConversion(duration) {
var portions = [];
var msInDay = 1000 * 60 * 60 * 24
var days = Math.trunc(duration / msInDay);
if (days > 0 ) {
portions.push(days + (days === 1 ? " day" : " days"))
duration = duration - (days * msInDay)
}
var msInHour = 1000 * 60 * 60;
var hours = Math.trunc(duration / msInHour);
if (hours > 0) {
portions.push(hours + (hours === 1 ? ' hour' : ' hours'));
duration = duration - (hours * msInHour);
}
var msInMinute = 1000 * 60;
var minutes = Math.trunc(duration / msInMinute);
if (minutes > 0) {
portions.push(minutes + (minutes === 1 ? ' minute' : ' minutes'));
duration = duration - (minutes * msInMinute);
}
var seconds = Math.trunc(duration / 1000);
if (seconds > 0) {
portions.push(seconds + (seconds === 1 ? ' second' : ' seconds'));
}
return portions.join(' ');
}
console.log(timeConversion((60 * 60 * 1000) + (59 * 60 * 1000) + (59 * 1000)));
console.log(timeConversion((60 * 60 * 1000) + (59 * 60 * 1000)));
console.log(timeConversion((60 * 60 * 1000)));
console.log(timeConversion((60 * 60 * 1000) + (59 * 1000)));
console.log(timeConversion((59 * 60 * 1000) + (59 * 1000)));
console.log(timeConversion((59 * 1000)));