Convert seconds to days, hours, minutes and seconds - 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?

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))

Related

Get difference between two times with ss.[milisecond] format [duplicate]

I have this function which formats seconds to time
function secondsToTime(secs){
var hours = Math.floor(secs / (60 * 60));
var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
return minutes + ":" + seconds;
}
it works great but i need a function to turn milliseconds to time and I cant seem to understand what i need to do to this function to return time in this format
mm:ss.mill
01:28.5568
Lots of unnecessary flooring in other answers. If the string is in milliseconds, convert to h:m:s as follows:
function msToTime(s) {
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return hrs + ':' + mins + ':' + secs + '.' + ms;
}
If you want it formatted as hh:mm:ss.sss then use:
function msToTime(s) {
// Pad to 2 or 3 digits, default is 2
function pad(n, z) {
z = z || 2;
return ('00' + n).slice(-z);
}
var ms = s % 1000;
s = (s - ms) / 1000;
var secs = s % 60;
s = (s - secs) / 60;
var mins = s % 60;
var hrs = (s - mins) / 60;
return pad(hrs) + ':' + pad(mins) + ':' + pad(secs) + '.' + pad(ms, 3);
}
console.log(msToTime(55018))
Using some recently added language features, the pad function can be more concise:
function msToTime(s) {
// Pad to 2 or 3 digits, default is 2
var pad = (n, z = 2) => ('00' + n).slice(-z);
return pad(s/3.6e6|0) + ':' + pad((s%3.6e6)/6e4 | 0) + ':' + pad((s%6e4)/1000|0) + '.' + pad(s%1000, 3);
}
// Current hh:mm:ss.sss UTC
console.log(msToTime(new Date() % 8.64e7))
Here is my favourite one-liner solution:
new Date(12345 * 1000).toISOString().slice(11, -1); // "03:25:45.000"
Method Date.prototype.toISOString() returns a string in the simplified extended ISO format (ISO 8601), which is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ. This method is supported in all modern browsers (IE9+) and Node.
This one-liner is limited to a range of one day, which is fine if you use it to format milliseconds up to 24 hours (i.e. ms < 86400000). The following code is able to format correctly any number of milliseconds (shaped in a handy prototype method):
/**
* Convert (milli)seconds to time string (hh:mm:ss[:mss]).
*
* #param Boolean seconds
*
* #return String
*/
Number.prototype.toTimeString = function(seconds) {
var _24HOURS = 8.64e7; // 24*60*60*1000
var ms = seconds ? this * 1000 : this,
endPos = ~(4 * !!seconds), // to trim "Z" or ".sssZ"
timeString = new Date(ms).toISOString().slice(11, endPos);
if (ms >= _24HOURS) { // to extract ["hh", "mm:ss[.mss]"]
var parts = timeString.split(/:(?=\d{2}:)/);
parts[0] -= -24 * Math.floor(ms / _24HOURS);
timeString = parts.join(":");
}
return timeString;
};
console.log( (12345 * 1000).toTimeString() ); // "03:25:45.000"
console.log( (123456 * 789).toTimeString() ); // "27:03:26.784"
console.log( 12345. .toTimeString(true) ); // "03:25:45"
console.log( 123456789. .toTimeString(true) ); // "34293:33:09"
function millisecondsToTime(milli)
{
var milliseconds = milli % 1000;
var seconds = Math.floor((milli / 1000) % 60);
var minutes = Math.floor((milli / (60 * 1000)) % 60);
return minutes + ":" + seconds + "." + milliseconds;
}
Why not use the Date object like this?
let getTime = (milli) => {
let time = new Date(milli);
let hours = time.getUTCHours();
let minutes = time.getUTCMinutes();
let seconds = time.getUTCSeconds();
let milliseconds = time.getUTCMilliseconds();
return hours + ":" + minutes + ":" + seconds + ":" + milliseconds;
}
https://jsfiddle.net/4sdkpso7/6/
function millisecondsToTime(millisecs){
var ms = Math.abs(millisecs) % 1000;
var secs = (millisecs < 0 ? -1 : 1) * ((Math.abs(millisecs) - ms) / 1000);
ms = '' + ms;
ms = '000'.substring(ms.length) + ms;
return secsToTime(secs) + '.' + ms;
}
Here is a filter that use:
app.filter('milliSecondsToTimeCode', function () {
return function msToTime(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 + "." + milliseconds;
};
});
Just add it to your expression as such
{{milliseconds | milliSecondsToTimeCode}}
Editing RobG's solution and using JavaScript's Date().
function msToTime(ms) {
function addZ(n) {
return (n<10? '0':'') + n;
}
var dt = new Date(ms);
var hrs = dt.getHours();
var mins = dt.getMinutes();
var secs = dt.getSeconds();
var millis = dt.getMilliseconds();
var tm = addZ(hrs) + ':' + addZ(mins) + ':' + addZ(secs) + "." + millis;
return tm;
}
Prons:
simple and clean code; easy to modify for your needs
support any amount of hours (>24 hrs is ok)
format time as 00:00:00.0
You can put it into a helper file
export const msecToTime = ms => {
const milliseconds = ms % 1000
const seconds = Math.floor((ms / 1000) % 60)
const minutes = Math.floor((ms / (60 * 1000)) % 60)
const hours = Math.floor((ms / (3600 * 1000)) % 3600)
return `${hours < 10 ? '0' + hours : hours}:${minutes < 10 ? '0' + minutes : minutes}:${
seconds < 10 ? '0' + seconds : seconds
}.${milliseconds}`
}
This worked for me:
var dtFromMillisec = new Date(secs*1000);
var result = dtFromMillisec.getHours() + ":" + dtFromMillisec.getMinutes() + ":" + dtFromMillisec.getSeconds();
JSFiddle
const monthNames = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
];
export function getFormattedDateAndTime(startDate) {
if (startDate != null) {
var launchDate = new Date(startDate);
var day = launchDate.getUTCDate();
var month = monthNames[launchDate.getMonth()];
var year = launchDate.getFullYear();
var min = launchDate.getMinutes();
var hour = launchDate.getHours();
var time = launchDate.toLocaleString('en-US', { hour: 'numeric', minute: 'numeric', hour12: true });
return day + " " + month + " " + year + " - " + time + "" ;
}
return "";
}
function msToTime(s) {
var d = new Date(s);
var datestring = ("0" + d.getDate()).slice(-2) + "-" + ("0"+(d.getMonth()+1)).slice(-2) + "-" +
d.getFullYear() + " "
+ ("0" + d.getHours()).slice(-2)
+ ":" + ("0" + d.getMinutes()).slice(-2)
+ ":" + ("0" + d.getSeconds()).slice(-2)
+"."+d.getMilliseconds();
return datestring;
}
output
16-10-2019 18:55:32.605
var
/**
* Parses time in milliseconds to time structure
* #param {Number} ms
* #returns {Object} timeStruct
* #return {Integer} timeStruct.d days
* #return {Integer} timeStruct.h hours
* #return {Integer} timeStruct.m minutes
* #return {Integer} timeStruct.s seconds
*/
millisecToTimeStruct = function (ms) {
var d, h, m, s;
if (isNaN(ms)) {
return {};
}
d = ms / (1000 * 60 * 60 * 24);
h = (d - ~~d) * 24;
m = (h - ~~h) * 60;
s = (m - ~~m) * 60;
return {d: ~~d, h: ~~h, m: ~~m, s: ~~s};
},
toFormattedStr = function(tStruct){
var res = '';
if (typeof tStruct === 'object'){
res += tStruct.m + ' min. ' + tStruct.s + ' sec.';
}
return res;
};
// client code:
var
ms = new Date().getTime(),
timeStruct = millisecToTimeStruct(ms),
formattedString = toFormattedStr(timeStruct);
alert(formattedString);
var secondsToTime = function(duration) {
var date = new Date(duration);
return "%hours:%minutes:%seconds:%milliseconds"
.replace('%hours', date.getHours())
.replace('%minutes', date.getMinutes())
.replace('%seconds', date.getSeconds())
.replace('%milliseconds', date.getMilliseconds());
}
try this function :-
function msToTime(ms) {
var d = new Date(null)
d.setMilliseconds(ms)
return d.toLocaleTimeString("en-US")
}
var ms = 4000000
alert(msToTime(ms))
A possible solution that worked for my case. It turns milliseconds into hh:ss time:
function millisecondstotime(ms) {
var x = new Date(ms);
var y = x.getHours();
if (y < 10) {
y = '0' + y;
}
var z = x.getMinutes();
if (z < 10) {
z = '0' + z;
}
return y + ':' + z;
}
This is the solution I got and working so good!
function msToHuman(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);
return hours + "hrs " minutes + "min " + seconds + "sec " + milliseconds + 'ms';
}
Most of the answers don't cover cases where there is more than 24h. This one does.
I suggest extending Date object:
class SuperDate extends Date {
get raceTime() {
return Math.floor(this/36e5).toString().padStart(2,'0')
+ this.toISOString().slice(13, -1)
}
}
console.log('marathon', new SuperDate(11235200).raceTime)
console.log('ironman', new SuperDate(40521100).raceTime)
console.log('spartathlon', new SuperDate(116239000).raceTime)
console.log('epoch', new SuperDate(new Date()).raceTime)
This approach works great with Firestore Timestamp objects which are similar to what you need:
class SuperDate extends Date {
fromFirestore (timestamp) {
return new SuperDate(timestamp.seconds * 1000 + timestamp.nanoseconds / 1000000)
}
get raceTime() {
return Math.floor(this/36e5).toString().padStart(2,'0')
+ this.toISOString().slice(13, -1)
}
}
const timestamp = {seconds: 11235, nanoseconds: 200000000}
console.log('timestamp', new SuperDate().fromFirestore(timestamp))
console.log('marathon', new SuperDate().fromFirestore(timestamp).raceTime)
Simplest Way
let getTime = (Time)=>{
let Hours = Time.getHours();
let Min = Time.getMinutes();
let Sec = Time.getSeconds();
return `Current time ${Hours} : ${Min} : ${Sec}`;
}
console.log(getTime(new Date()));
An Easier solution would be the following:
var d = new Date();
var n = d.getMilliseconds();

Human readable duration format - Codewars

It's a task to build a String with time values and units, separated with ", "
link to Codewars
I'm stuck at the end. I wrote this code:
function formatDuration (seconds) {
// return now if seconds = 0
if (seconds == 0) {
return "now";
}
// count values of each unit
let Y = Math.floor(seconds / 31536000);
let D = Math.floor(seconds / 86400 - Y * 365);
let H = Math.floor(seconds / 3600 - D * 24 - Y * 8760);
let M = Math.floor(seconds / 60 - H * 60 - D * 1440 - Y * 525600);
let S = seconds - M * 60 - H * 3600 - D * 86400 - Y * 31536000;
// build time values + units
let YY = Y + " year";
if (Y != 1) {
YY += "s"
}
let DD = D + " day";
if (D != 1) {
DD += "s"
}
let HH = H + " hour";
if (H != 1) {
HH += "s"
}
let MM = M + " minute";
if (M != 1) {
MM += "s"
}
let SS = S + " second";
if (S != 1) {
SS += "s"
}
let timeDigits = [S, M, H, D, Y];
let timeWhole = [SS, MM, HH, DD, YY];
// check which units are not 0's
let notZeros = [];
for (let i in timeDigits) {
if (timeDigits[i] != 0) {
notZeros += i;
}
}
// iterate notZeros through timeWhole and build the answer
let format = "";
for (let j = 0; j < notZeros.length; j++) {
if (notZeros.length != 1) {
// if it's the last unit
if (j == notZeros[0]) {
format = " and " + timeWhole[notZeros[j]] + format;
}
// if it's another unit
else if (j != notZeros[notZeros.length-1]){
format = ", " + timeWhole[notZeros[j]] + format;
}
// if it's the first unit
else {
format = timeWhole[notZeros[j]] + format;
}
}
// if it's a single unit
else {
format = timeWhole[notZeros[j]];
}
}
return format;
}
It works in most cases. on 100/110 tests made by Codewars results are green:
Test Passed: Value == '6 years, 192 days, 13 hours, 3 minutes and 54 seconds'
But on 10 of them I get this:
Expected: '4 years, 68 days, 3 hours and 4 minutes', instead got: ', 4 years, 68 days and 3 hours, 4 minutes'
Expected: '97 days, 10 hours and 26 seconds', instead got: ', 97 days, 10 hours and 26 seconds'
Expected: '33 days, 59 minutes and 55 seconds', instead got: ', 33 days, 59 minutes and 55 seconds'
Expected: '114 days, 46 minutes and 34 seconds', instead got: ', 114 days, 46 minutes and 34 seconds'
Problem is the ", " in the beginning of these, but I can't find any regularity in it.
Also on the failed test with Years unit, Hours and Minutes are shuffled.
I think an easier approach would be, instead of the whole last section, construct an array of strings - eg ['6 years', '192 days', ...] - then pop the last off, join the rest by a comma, then add on and to the final one (if there's any of them other than the final one):
const Y = Math.floor(seconds / 31536000);
const D = Math.floor(seconds / 86400 - Y * 365);
const H = Math.floor(seconds / 3600 - D * 24 - Y * 8760);
const M = Math.floor(seconds / 60 - H * 60 - D * 1440 - Y * 525600);
const S = seconds - M * 60 - H * 3600 - D * 86400 - Y * 31536000;
const plural = num => num === 1 ? '' : 's';
const YY = Y ? Y + ' year' + plural(Y) : null;
const DD = D ? D + ' day' + plural(D) : null;
const HH = H ? H + ' hour' + plural(H) : null;
const MM = M ? M + ' minute' + plural(M) : null;
const SS = S ? S + ' second' + plural(S) : null;
const nonNullValues = [YY, DD, HH, MM, SS].filter(Boolean);
const last = nonNullValues.pop();
return nonNullValues.length === 0
? last
: nonNullValues.join(', ') + ' and ' + last;
function formatDuration (seconds) {
if(!seconds) return 'now';
const units = {
year : 24 * 60 * 60 * 1 * 365,
day : 24 * 60 * 60 * 1,
hour : 60 * 60 * 1,
minute: 60 * 1,
second: 1
}
const sequence = ['year','day','hour','minute','second']
const calculateTime = (s) => {
let remaningTime = s
return sequence.reduce((acc,key) => {
if(remaningTime >= units[key]) {
acc[key] = Math.floor(remaningTime/units[key])
remaningTime = (remaningTime % units[key])
}
return acc
},{})
}
const displayUnit = (num,str) => `${num} ${str}` + ((num == 1) ? '' : 's')
const displayString = (timeObj) => {
let result = ''
let lastResult = ''
let objKeys = Object.keys(timeObj)
if (objKeys.length <= 1) return displayUnit(timeObj[objKeys[0]],objKeys[0]);
objKeys.forEach(v => {
if (result && lastResult) {
result += `, ${lastResult}`
} else if(lastResult) {
result += `${lastResult}`
}
lastResult = displayUnit(timeObj[v] , v)
})
return `${result} and ${lastResult}`
}
const obj = calculateTime(seconds)
return displayString(obj)
}

How to convert seconds to minutes and hours in javascript

I have a count of seconds stored in variable seconds. I want to convert for example 1439 seconds to 23 minutes and 59 seconds. And if the time is greater than 1 hour (for example 9432 seconds), to 2 hours, 37 minutes and 12 seconds.
How can I achieve this?
I'm thinking of:
var sec, min, hour;
if(seconds<3600){
var a = Math.floor(seconds/60); //minutes
var b = seconds%60; //seconds
if (b!=1){
sec = "seconds";
}else{
sec = "second";
}
if(a!=1){
min = "minutes";
}else{
min = "minute";
}
$('span').text("You have played "+a+" "+min+" and "+b+" "+sec+".");
}else{
var a = Math.floor(seconds/3600); //hours
var x = seconds%3600;
var b = Math.floor(x/60); //minutes
var c = seconds%60; //seconds
if (c!=1){
sec = "seconds";
}else{
sec = "second";
}
if(b!=1){
min = "minutes";
}else{
min = "minute";
}
if(c!=1){
hour = "hours";
}else{
hour = "hour";
}
$('span').text("You have played "+a+" "+hour+", "+b+" "+min+" and "+c+" "+sec+".");
}
But that's a lot of code, and it has to be calculated each second. How can I shrink this up?
I think you would find this solution very helpful.
You modify the display format to fit your needs with something like this -
function secondsToHms(d) {
d = Number(d);
var h = Math.floor(d / 3600);
var m = Math.floor(d % 3600 / 60);
var s = Math.floor(d % 3600 % 60);
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 hDisplay + mDisplay + sDisplay;
}
The builtin JavaScript Date object can simplify the required code
toTime(seconds) {
var date = new Date(null);
date.setSeconds(seconds);
return date.toISOString().substr(11, 8);
}
You can try this, i have used this successfully in the past
You should be able to add the minutes and seconds on easily
function secondsToTime(secs)
{
var hours = Math.floor(secs / (60 * 60));
var divisor_for_minutes = secs % (60 * 60);
var minutes = Math.floor(divisor_for_minutes / 60);
var divisor_for_seconds = divisor_for_minutes % 60;
var seconds = Math.ceil(divisor_for_seconds);
var obj = {
"h": hours,
"m": minutes,
"s": seconds
};
return obj;
}
Fiddle
You can change the object to
var obj = {
"h": hours + " hours",
"m": minutes + " minutes",
"s": seconds + " seconds"
};
I'm probably a bit late but you can achieve this kind of things using
https://momentjs.com/
myVar = moment(myVar).format('HH:mm');
moment provides A LOT of format for hours / dates etc.
A low fat way to do this is:
function seconds_to_days_hours_mins_secs_str(seconds)
{ // day, h, m and s
var days = Math.floor(seconds / (24*60*60));
seconds -= days * (24*60*60);
var hours = Math.floor(seconds / (60*60));
seconds -= hours * (60*60);
var minutes = Math.floor(seconds / (60));
seconds -= minutes * (60);
return ((0<days)?(days+" day, "):"")+hours+"h, "+minutes+"m and "+seconds+"s";
}
Thus
> seconds_to_days_hours_mins_secs_str(9432+60*60*24)
'1 days, 2h, 37m and 12s'
This is easy to understand and extend as needed.
Try this, Convert SEC to H:M:S.
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;
}
I found Wilson Lee's and Brian's code super useful! Here is how I adapted their code:
function formatTime(serverTimeinSeconds, elementId)
{ /* This converts seconds into days, hours, minutes and seconds timestring.
Requires JQuery if elementId argument is provided */
seconds = Math.floor(Number(serverTimeinSeconds));
days = Math.floor(seconds / (24*60*60));
seconds -= Math.floor(days * (24*60*60));
hours = Math.floor(seconds / (60*60));
seconds -= Math.floor(hours * (60*60));
minutes = Math.floor(seconds / (60));
seconds -= Math.floor(minutes * (60));
dDisplay = days > 0 ? days + (days == 1 ? ' day, ' : ' days, ') : '';
hDisplay = hours > 0 ? hours + (hours == 1 ? ' hour, ' : ' hours, ') : '';
mDisplay = minutes > 0 ? minutes + (minutes == 1 ? ' minute, ' : ' minutes, ') : '';
sDisplay = seconds > 0 ? seconds + (seconds == 1 ? ' second' : ' seconds') : '';
if (elementId != null) {
if (serverTimeinSeconds < 60) {
$(elementId).css('font-size', '15px');
$(elementId).html(sDisplay);
}
if (serverTimeinSeconds >= 60 && serverTimeinSeconds < 3600) {
$(elementId).css('font-size', '15px');
$(elementId).html(mDisplay + sDisplay);
}
if (serverTimeinSeconds >= 3600 && serverTimeinSeconds < 86400) {
$(elementId).css('font-size', '12px');
$(elementId).html(hDisplay + mDisplay + sDisplay);
}
if (serverTimeinSeconds >= 86400 && serverTimeinSeconds !== Infinity) {
$(elementId).css('font-size', '8px');
$(elementId).html(dDisplay + hDisplay + mDisplay + sDisplay);
}
}
return dDisplay + hDisplay + mDisplay + sDisplay;
}
Please install moment js after that import it,
import moment from 'moment'
let dateForm = (arg) => {
return moment.unix(arg).utc().format('H [hours,] m [minutes and] s [seconds]');
}
console.log(dateForm(11));
// 0 hours, 0 minutes and 11 seconds
console.log(dateForm(16060));
// 1 hours, 0 minutes and 0 seconds
const formatter = (seconds = 0) => {
const d = Number(secondsAmount);
const h = Math.floor(d / 3600);
const m = Math.floor((d % 3600) / 60);
const s = Math.floor((d % 3600) % 60);
const hDisplay = h > 0 ? `${h.toString().length > 1 ? `${h}` : `${0}${h}`}` : '00';
const mDisplay = m > 0 ? `${m.toString().length > 1 ? `${m}` : `${0}${m}`}` : '00';
const sDisplay = s > 0 ? `${s.toString().length > 1 ? `${s}` : `${0}${s}`}` : '00';
return `${hDisplay}:${mDisplay}:${sDisplay}`;
};
Will return this format human readable format 00:00:00
Built off R4nc1d's answer:
function secondsToTime(secs){
var h = Math.floor(secs / (60 * 60));
var divisor_for_minutes = secs % (60 * 60);
var m = Math.floor(divisor_for_minutes / 60);
var divisor_for_seconds = divisor_for_minutes % 60;
var s = Math.ceil(divisor_for_seconds);
return `${h?`${h}:`:""}${m?`${m}:${s}`:`${s}s`}`
}
This will return a human readable answer which looks like this. I used this for displaying the length of music tracks
time = secondsToTime(5)
console.log(time) // 5s
time = secondsToTime(50)
console.log(time) // 50s
time = secondsToTime(500)
console.log(time) // 8:20
time = secondsToTime(5000)
console.log(time) // 1:23:20
#pkerckhove has already mentioned moment as a great library to work with dates and times, and you can also use moment to directly format the seconds into OP's desired format, i.e.:
import moment from 'moment'
const myVar = 1439
console.log(
moment.unix(myVar).utc().format('H [hours,] m [minutes and] s [seconds]')
)
Will result in: 0 hours, 23 minutes and 59 seconds and,
import moment from 'moment'
const myVar = 9432
console.log(
moment.unix(myVar).utc().format('H [hours,] m [minutes and] s [seconds]')
)
Will result in: 2 hours, 37 minutes and 12 seconds
One way of doing it:
const formatDuration = totalSeconds => {
const hours = Math.floor(totalSeconds / 3600)
const minutes = Math.floor((totalSeconds % 3600) / 60)
const seconds = totalSeconds - hours * 3600 - minutes * 60
return [`${hours}h`, `${minutes}m`, `${seconds}s`]
.filter(item => item[0] !== '0')
.join(' ')
}
This method also works with a negative amount of time:
function CalculateTime(sec){
if(sec >= 0){
var h = Math.floor(sec / 3600);
var m = Math.floor(sec % 3600 / 60);
var s = Math.floor(sec % 3600 % 60);
}
else{
var h = Math.ceil(sec / 3600);
var m = Math.ceil(sec % 3600 / 60);
var s = Math.ceil(sec % 3600 % 60);
}
var hDisplay = h !== 0 ? h + (h == 1 ? " hour, " : " hours") + (m != 0 || s > 0 ? ", ":"") : "";
var mDisplay = m !== 0 ? m + (m == 1 ? " minute, " : " minutes") + (s != 0 ? " ":""): "";
var sDisplay = s !== 0 ? s + (s == 1 ? " second" : " seconds") : "";
return hDisplay + mDisplay + sDisplay;
}
for having the result with the time format " 00:00:00 " I added some changes to it.
function secondsToHms(seconds) {
let d = Number(seconds);
if(d <= 0){
return '00:00:00'
}else{
let h = Math.floor(d / 3600);
let m = Math.floor(d % 3600 / 60);
let s = Math.floor(d % 3600 % 60);
let hDisplay = h <= 9 ? '0'+ h+':' : h+ ":";
let mDisplay = m <= 9 ? '0'+ m+':' : m+ ":";
let sDisplay = s <= 9 ? '0'+ s : s;
return hDisplay + mDisplay + sDisplay;
}}
Try this :D
secondsToHms(d) {
d = Number(d);
var h = Math.floor(d / 3600);
var m = Math.floor(d % 3600 / 60);
var s = Math.floor(d % 3600 % 60);
var hDisplay = h > 0 ? h + (h == 1 ? "" : "") : "";
var mDisplay = m > 0 ? m + (m == 1 ? "" : "") : "";
var sDisplay = s > 0 ? s + (s == 1 ? "" : "") : "";
if (hDisplay != "") {
return (hDisplay.length > 1 ? hDisplay : '0' + hDisplay) + ":" + (mDisplay.length > 1 ? mDisplay : '0' + mDisplay) + ":" + (sDisplay.length > 1 ? sDisplay : '0' + sDisplay);
}
else if (mDisplay != "") {
return (mDisplay.length > 1 ? mDisplay : '0' + mDisplay) + ":" + (sDisplay.length > 1 ? sDisplay : '0' + sDisplay);
}
else if (sDisplay != "") {
return "00:" + (sDisplay.length > 1 ? sDisplay : '0' + sDisplay);
}
return "00:00"
}
Using the popular date-fns library
import { format, setSeconds, startOfDay } from 'date-fns'
export const hourMinSec = (secs: number, showHour = false): string => {
const tmpDate: Date = startOfDay(new Date())
const date: Date = setSeconds(tmpDate, secs)
const hour: number = date.getHours()
const hasHour: boolean = !!hour
if (hasHour && !showHour) console.warn('hourMinSec is hiding a non zero hour')
const strFormat: string = showHour ? 'H:mm:ss' : 'm:ss'
return format(date, strFormat)
}
OR the same code with a more functional approach (adding lodash flow in the mix)
import { setSeconds, startOfDay } from 'date-fns/fp'
import { format } from 'date-fns'
import { flow } from 'lodash-es'
export const hourMinSec = (secs: number, showHour = false): string => {
const date: Date = flow(startOfDay, setSeconds(secs))(new Date())
const hour: number = date.getHours()
const hasHour: boolean = !!hour
if (hasHour && !showHour) console.warn('hourMinSec is hiding a non zero hour')
const strFormat: string = showHour ? 'H:mm:ss' : 'm:ss'
return format(date, strFormat)
}
Usage:
hourMinSec(100) // 1:40
hourMinSec(3700) // 1:40 // will warn in logs that a non zero hour is hidden
hourMinSec(100, true) // 0:01:40
hourMinSec(3700, true) // 1:01:40
This met my needs but you could adapt this by changing the showHour = false parameter to be a strFormat = 'm:ss' parameter instead to support more flexible formatting.
const minutes = Math.floor(duration / 60);
const seconds = Math.floor(duration - minutes * 60);
const time = `${minutes < 10 ? `0${minutes}` : minutes}
:${seconds < 10 ? `0${seconds}` : seconds}`; // result: 02:23
useCountDown Hook
// useCountDown.js
import { useEffect, useState } from "react"
const useCountDown = (minutes) => {
const [seconds, setSeconds] = useState(minutes * 60)
useEffect(() => {
const interval = setInterval(() => {
setSeconds(seconds - 1)
}, 1000)
return () => clearInterval(interval)
}, [seconds])
return getReturnValues2(seconds)
}
const getReturnValues2 = (countDown) => {
const minutes = Math.floor(countDown / 60)
const seconds = countDown % 60
return `${padTo2Digits(minutes)}:${padTo2Digits(seconds)}`
}
function padTo2Digits(num) {
return num.toString().padStart(2, "0")
}
export default useCountDown
How to use?
//React Component
import useCountDown from '../hooks/useCountDown'
function App() {
const countDown = useCountDown(5) // 5 Minutes
return (
<h1> {countDown} </h1> // MM:SS
)
}
You can tweak as per your needs.
Convert to H:M
Number(moment.duration(Number(37320), 'seconds').hours()+'.'+moment.duration(Number(37320),'seconds').minutes())

Averaging Times using Javascript

I am building an app using Phonegap and JQuery.
The app stores ( using window.localStorage ) a set of times (no more than 10) in the format.
HH:MM:SS.mm
There are a number of 'Zero' times in the list eg '00:00:00.00' which iphonegap, javascript
eliminate using..
function removeA(arr){
var what, a= arguments, L= a.length, ax;
while(L> 1 && arr.length){
what= a[--L];
while((ax= arr.indexOf(what))!= -1){
arr.splice(ax, 1);
}
}
return arr;
}
scores.sort();
removeA(scores,'00:00:00.00');
so that i'm left with the fastest time first, and only the times that have a value.
I need to produce from the remaining values the average of those times.
eg: 00:00:03.00
00:00:05.00
00:00:02.00
00:00:06.00
= 00:00:04.00
thanks in advance :)
var times= [ '00:00:03.00', '00:00:05.00', '00:00:02.00', '00:00:06.00'],
date = 0,
result = '';
function offsetify(t){
return t < 10 ? '0' + t : t;
}
for(var x = 0; x < times.length; x++ ) {
var tarr = times[x].split(':');
date += new Date(0, 0, 0, tarr[0], tarr[1], tarr[2].split('.')[0], tarr[2].split('.')[1]).getTime();
}
var avg = new Date(date/times.length);
result = offsetify(avg.getHours()) + ':' + offsetify(avg.getMinutes()) + ':' + offsetify(avg.getSeconds()) + '.' + offsetify(avg.getMilliseconds());
DEMO
if you are going to also have millisecond values and you want to consider them, then convert the times into millisecond. Now, add them and divide them by the number of records. Else, convert everything to seconds and find the average - you get the answer in seconds, of course.
The conversion is quite simple if take little time to think over it. Here's how to convert.
To milliseconds:
function convertToMS(timeStr) { // timeStr in format 'HH:MM:SS.mm'
var I = parseInt; // for brevity
var t = timeStr,
h = I( t.substr(0,2) ),
m = I( t.substr(3,2) ),
s = I( t.substr(6,2) ),
ms = I( t.substr(9,2) );
return h * 3600000 + m * 60000 + s * 1000 + ms;
}
To seconds:
function convertToS(timeStr) { // timeStr in format 'HH:MM:SS[.mm]' -- .mm is ignored.
var I = parseInt; // for brevity
var t = timeStr,
h = I( t.substr(0,2) ),
m = I( t.substr(3,2) ),
s = I( t.substr(6,2) );
return h * 3600 + m * 60 + s;
}
After the conversion's done, add them up and find the average.
UPDATE:
To convert back to the format 'HH:MM:SS.mm', we change back the time into 'chunks' of hours, minutes, seconds and (if applicable) milliseconds.
function chunkifyFromSec(time) { // time in s
var t = "",
h = Math.floor(time / 3600),
m = Math.floor( (t - (h * 3600)) / 60 ),
s = t - (h * 3600) - (m * 60);
return {
HH: h, MM: m, SS: s, mm: 0
};
}
function chunkifyFromMS(time) { // time in ms
var t = "",
h = Math.floor(time / 3600000),
m = Math.floor( (t - (h * 3600000)) / 60000 ),
s = Math.floor( (t - (h * 3600000) - (m * 60000)) / 1000 ),
mm = t - (h * 3600000) - (m * 600000) - (s * 1000);
return {
HH: h, MM: m, SS: s, mm: mm
};
}
Then, we return the string in the format 'HH:MM:SS.mm' using this:
function toTimeStr(chunks) {
return
(chunks.HH < 0 ? '0' : '') + chunks.HH + ":"
+= (chunks.MM < 0 ? '0' : '') + chunks.MM + ":"
+= (chunks.SS < 0 ? '0' : '') + chunks.SS + "."
+= (chunks.mm < 0 ? '0' : '') + chunks.mm
}
I don't have much experience with Javascript so I might have some syntax errors but I think you could do something like
var i = 0;
var totalTime = 0.0;
for (i=0; i < scores.length; i++) {
var hours = parseFloat(scores[i].substring(0, 2)); //get numeric value for hours
var minutes = parseFloat(scores[i].substring(3,5)); //get numeric value for minutes
var seconds = parseFloat(scores[i].substring(6)); //get numeric for the seconds
var time = ((hours * 60) + minutes) * 60 + seconds; //60 minutes in an hour, 60 seconds in a minute
totalTime += time;
}
var avgTime = totalTime/scores.length;
var avgHours = Math.floor(avgTime / 3600); //60*60
var avgHoursStr = String(avgHours);
var avgMinutes = Math.floor((avgTime % 3600) / 60); //mod to get rid of the hours
var avgMinutesStr = String(avgMinutes);
var avgSeconds = avgTime - avgHours*3600 - avgMinutes*60; //get the remainder. Can't use mod due to decimal
var avgSeconds = String(avgSeconds);
//Concat strings. Add the ":" spacers. Where necessary, add leading 0
var avgStr = (avgHoursStr.length > 1 ? "" : "0") + avgHoursStr + ":" + (avgMinutesStr.length > 1 ? "" : "0") + avgMinuteStr + ":" + avgSecondsStr;
[EDIT - Thanks to Parth Thakkar for point out my problem]
To return the answer in milliseconds or seconds:
var times = ["00:00:03.00", "00:00:05.00", "00:00:02.00", "00:00:06.00"];
function averageTimes(times,unit) {
if (!times) {
return false;
}
else {
var totalMilliseconds = 0, hours, minutes, seconds, milliseconds, parts;
for (var i = 0, len = times.length; i < len; i++) {
parts = times[i].split(':');
hours = parseInt(parts[0], 10) * 3600000;
minutes = parseInt(parts[1], 10) * 60000;
seconds = parseInt(parts[2].split('.')[0], 10) * 1000;
milliseconds = parseInt(parts[2].split('.')[1], 10);
totalMilliseconds += (hours + minutes + seconds + milliseconds);
}
if (!unit || unit.toLowerCase() == 'ms'){
return totalMilliseconds/times.length + ' milliseconds';
}
else if (unit.toLowerCase() == 's') {
return (totalMilliseconds/1000)/times.length + ' seconds';
}
}
}
// parameters:
// times: an array of times in your supplied format, 'HH:MM:SS:mm',
// unit: a string ('ms' or 's'), denoting whether to return milliseconds or seconds.
var average = averageTimes(times,'s');
console.log(average);​
JS Fiddle demo.
References:
for(){/*...*/} loop.
parseInt().
split().
toLowerCase().

Convert time interval given in seconds into more human readable form

I need a code snippet for converting amount of time given by number of seconds into some human readable form. The function should receive a number and output a string like this:
34 seconds
12 minutes
4 hours
5 days
4 months
1 year
No formatting required, hard-coded format will go.
function secondsToString(seconds)
{
var numyears = Math.floor(seconds / 31536000);
var numdays = Math.floor((seconds % 31536000) / 86400);
var numhours = Math.floor(((seconds % 31536000) % 86400) / 3600);
var numminutes = Math.floor((((seconds % 31536000) % 86400) % 3600) / 60);
var numseconds = (((seconds % 31536000) % 86400) % 3600) % 60;
return numyears + " years " + numdays + " days " + numhours + " hours " + numminutes + " minutes " + numseconds + " seconds";
}
With help of Royi we've got code that outputs time interval in a human readable form:
function millisecondsToStr (milliseconds) {
// TIP: to find current time in milliseconds, use:
// var current_time_milliseconds = new Date().getTime();
function numberEnding (number) {
return (number > 1) ? 's' : '';
}
var temp = Math.floor(milliseconds / 1000);
var years = Math.floor(temp / 31536000);
if (years) {
return years + ' year' + numberEnding(years);
}
//TODO: Months! Maybe weeks?
var days = Math.floor((temp %= 31536000) / 86400);
if (days) {
return days + ' day' + numberEnding(days);
}
var hours = Math.floor((temp %= 86400) / 3600);
if (hours) {
return hours + ' hour' + numberEnding(hours);
}
var minutes = Math.floor((temp %= 3600) / 60);
if (minutes) {
return minutes + ' minute' + numberEnding(minutes);
}
var seconds = temp % 60;
if (seconds) {
return seconds + ' second' + numberEnding(seconds);
}
return 'less than a second'; //'just now' //or other string you like;
}
If you are interested in an existing javascript library that does the job very well, you may want to check moment.js.
More specifically, the relevant moment.js piece for your question is durations.
Here are some examples of how you can take advantage of it to achieve your task:
var duration = moment.duration(31536000);
// Using the built-in humanize function:
console.log(duration.humanize()); // Output: "9 hours"
console.log(duration.humanize(true)); // Output: "in 9 hours"
moment.js has built-in support for 50+ human languages, so if you use the humanize() method you get multi-language support for free.
If you want to display the exact time information, you can take advantage of the moment-precise-range plug-in for moment.js that was created exactly for this purpose:
console.log(moment.preciseDiff(0, 39240754000);
// Output: 1 year 2 months 30 days 5 hours 12 minutes 34 seconds
One thing to note is that currently moment.js does not support weeks / days (in week) for duration object.
Hope this helps!
Took a swing based on #Royi's response:
/**
* Translates seconds into human readable format of seconds, minutes, hours, days, and years
*
* #param {number} seconds The number of seconds to be processed
* #return {string} The phrase describing the amount of time
*/
function forHumans ( seconds ) {
var levels = [
[Math.floor(seconds / 31536000), 'years'],
[Math.floor((seconds % 31536000) / 86400), 'days'],
[Math.floor(((seconds % 31536000) % 86400) / 3600), 'hours'],
[Math.floor((((seconds % 31536000) % 86400) % 3600) / 60), 'minutes'],
[(((seconds % 31536000) % 86400) % 3600) % 60, 'seconds'],
];
var returntext = '';
for (var i = 0, max = levels.length; i < max; i++) {
if ( levels[i][0] === 0 ) continue;
returntext += ' ' + levels[i][0] + ' ' + (levels[i][0] === 1 ? levels[i][1].substr(0, levels[i][1].length-1): levels[i][1]);
};
return returntext.trim();
}
Nice thing about mine is that there is no repetitive ifs, and won't give you 0 years 0 days 30 minutes 1 second for example.
For example:
forHumans(60) outputs 1 minute
forHumans(3600) outputs 1 hour
and forHumans(13559879) outputs 156 days 22 hours 37 minutes 59 seconds
Try following:
seconds = ~~(milliseconds / 1000);
minutes = ~~(seconds / 60);
hours = ~~(minutes / 60);
days = ~~(hours / 24);
weeks = ~~(days / 7);
year = ~~(days / 365);
Note:
A usual year has 365 days. A leap year has 366 days, so you need additional check if this is an issue for you.
The similar problem with daylight saving. Some days have 23 and some 25 hours when time's changed.
Conclusion: this is a rude but small and simple snippet :)
millisToTime = function(ms){
x = ms / 1000;
seconds = Math.round(x % 60);
x /= 60;
minutes = Math.round(x % 60);
x /= 60;
hours = Math.round(x % 24);
x /= 24;
days = Math.round(x);
return {"Days" : days, "Hours" : hours, "Minutes" : minutes, "Seconds" : seconds};
}
This will take milliseconds as an int, and give you an JSON object containing all the info you could need
Way more simple and readable.
milliseconds = 12345678;
mydate=new Date(milliseconds);
humandate=mydate.getUTCHours()+" hours, "+mydate.getUTCMinutes()+" minutes and "+mydate.getUTCSeconds()+" second(s)";
Which gives:
"3 hours, 25 minutes and 45 second(s)"
To Convert time in millisecond to human readable format.
function timeConversion(millisec) {
var seconds = (millisec / 1000).toFixed(1);
var minutes = (millisec / (1000 * 60)).toFixed(1);
var hours = (millisec / (1000 * 60 * 60)).toFixed(1);
var days = (millisec / (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"
}
}
Thanks to #Dan / # Royi for the logic. However the implementation doesn't build time string like XX days, XX mins. I adjusted their code a bit:
function millisecondsToStr( milliseconds ) {
let temp = milliseconds / 1000;
const years = Math.floor( temp / 31536000 ),
days = Math.floor( ( temp %= 31536000 ) / 86400 ),
hours = Math.floor( ( temp %= 86400 ) / 3600 ),
minutes = Math.floor( ( temp %= 3600 ) / 60 ),
seconds = temp % 60;
if ( days || hours || seconds || minutes ) {
return ( years ? years + "y " : "" ) +
( days ? days + "d " : "" ) +
( hours ? hours + "h " : "" ) +
( minutes ? minutes + "m " : "" ) +
Number.parseFloat( seconds ).toFixed( 2 ) + "s";
}
return "< 1s";
}
When one runs it
console.log("=", millisecondsToStr( 1540545689739 - 1540545684368 ));
console.log("=", millisecondsToStr( 351338536000 ));
The results look like:
= 5.37s
= 11y 51d 10h 2m 16.00s
Adding to the myriad of methods, here's a cheap and short way to retrieve a human readable time with only a single time unit.
const timeScalars = [1000, 60, 60, 24, 7, 52];
const timeUnits = ['ms', 'secs', 'mins', 'hrs', 'days', 'weeks', 'years'];
const getHumanReadableTime = (ms, dp = 0) => {
let timeScalarIndex = 0, scaledTime = ms;
while (scaledTime > timeScalars[timeScalarIndex]) {
scaledTime /= timeScalars[timeScalarIndex++];
}
return `${scaledTime.toFixed(dp)} ${timeUnits[timeScalarIndex]}`;
};
Example outputs:
getHumanReadableTime(512000);
getHumanReadableTime(5120000);
getHumanReadableTime(51200000);
getHumanReadableTime(51200000, 2);
getHumanReadableTime(51200000, 6);
/*
Output:
'9 min'
'1 hrs'
'14 hrs'
'14.22 hrs'
'14.222222 hrs'
*/
function millisecondsToString(milliseconds) {
var oneHour = 3600000;
var oneMinute = 60000;
var oneSecond = 1000;
var seconds = 0;
var minutes = 0;
var hours = 0;
var result;
if (milliseconds >= oneHour) {
hours = Math.floor(milliseconds / oneHour);
}
milliseconds = hours > 0 ? (milliseconds - hours * oneHour) : milliseconds;
if (milliseconds >= oneMinute) {
minutes = Math.floor(milliseconds / oneMinute);
}
milliseconds = minutes > 0 ? (milliseconds - minutes * oneMinute) : milliseconds;
if (milliseconds >= oneSecond) {
seconds = Math.floor(milliseconds / oneSecond);
}
milliseconds = seconds > 0 ? (milliseconds - seconds * oneSecond) : milliseconds;
if (hours > 0) {
result = (hours > 9 ? hours : "0" + hours) + ":";
} else {
result = "00:";
}
if (minutes > 0) {
result += (minutes > 9 ? minutes : "0" + minutes) + ":";
} else {
result += "00:";
}
if (seconds > 0) {
result += (seconds > 9 ? seconds : "0" + seconds) + ":";
} else {
result += "00:";
}
if (milliseconds > 0) {
result += (milliseconds > 9 ? milliseconds : "0" + milliseconds);
} else {
result += "00";
}
return result;
}
Here is my take.
Feel free to play around with it in the jsbin.
// This returns a string representation for a time interval given in milliseconds
// that appeals to human intuition and so does not care for leap-years,
// month length irregularities and other pesky nuisances.
const human_millis = function (ms, digits=1) {
const levels=[
["ms", 1000],
["sec", 60],
["min", 60],
["hrs", 24],
["days", 7],
["weeks", (30/7)], // Months are intuitively around 30 days
["months", 12.1666666666666666], // Compensate for bakari-da in last step
["years", 10],
["decades", 10],
["centuries", 10],
["millenia", 10],
];
var value=ms;
var name="";
var step=1;
for(var i=0, max=levels.length;i<max;++i){
value/=step;
name=levels[i][0];
step=levels[i][1];
if(value < step){
break;
}
}
return value.toFixed(digits)+" "+name;
}
console.clear();
console.log("---------");
console.log(human_millis(1));
console.log(human_millis(10));
console.log(human_millis(100));
console.log(human_millis(1000));
console.log(human_millis(1000*60));
console.log(human_millis(1000*60*60));
console.log(human_millis(1000*60*60*24));
console.log(human_millis(1000*60*60*24*7));
console.log(human_millis(1000*60*60*24*30));
console.log(human_millis(1000*60*60*24*365));
console.log(human_millis(1000*60*60*24*365*10));
console.log(human_millis(1000*60*60*24*365*10*10));
console.log(human_millis(1000*60*60*24*365*10*10*10));
console.log(human_millis(1000*60*60*24*365*10*10*10*10));
If you use Typescript type and cast to make it work
let name : string | number = "";
let step : string | number =1;
for(var i=0, max=levels.length;i<max;++i){
value/= step as number;
name=levels[i][0];
step=levels[i][1];
if(value < step){
break;
}
}
Output:
"---------"
"1.0 ms"
"10.0 ms"
"100.0 ms"
"1.0 sec"
"1.0 min"
"1.0 hrs"
"1.0 days"
"1.0 weeks"
"1.0 months"
"1.0 years"
"1.0 decades"
"1.0 centuries"
"1.0 millenia"
"10.0 millenia"
This function outputs seconds in this format : 11h 22m, 1y 244d, 42m 4s etc
Set the max variable to show as many identifiers as you want.
function secondsToString (seconds) {
var years = Math.floor(seconds / 31536000);
var max =2;
var current = 0;
var str = "";
if (years && current<max) {
str+= years + 'y ';
current++;
}
var days = Math.floor((seconds %= 31536000) / 86400);
if (days && current<max) {
str+= days + 'd ';
current++;
}
var hours = Math.floor((seconds %= 86400) / 3600);
if (hours && current<max) {
str+= hours + 'h ';
current++;
}
var minutes = Math.floor((seconds %= 3600) / 60);
if (minutes && current<max) {
str+= minutes + 'm ';
current++;
}
var seconds = seconds % 60;
if (seconds && current<max) {
str+= seconds + 's ';
current++;
}
return str;
}
With the help of Dan answer, I came up with this if you want to calculate the difference between the post created time (from DB it should be retrieved as UTC) and the users system time and then show them the elapsed time, you could use below function
function dateToStr(input_date) {
input_date= input_date+" UTC";
// convert times in milliseconds
var input_time_in_ms = new Date(input_date).getTime();
var current_time_in_ms = new Date().getTime();
var elapsed_time = current_time_in_ms - input_time_in_ms;
function numberEnding (number) {
return (number > 1) ? 's' : '';
}
var temp = Math.floor(elapsed_time / 1000);
var years = Math.floor(temp / 31536000);
if (years) {
return years + ' year' + numberEnding(years);
}
//TODO: Months! Maybe weeks?
var days = Math.floor((temp %= 31536000) / 86400);
if (days) {
return days + ' day' + numberEnding(days);
}
var hours = Math.floor((temp %= 86400) / 3600);
if (hours) {
return hours + ' hour' + numberEnding(hours);
}
var minutes = Math.floor((temp %= 3600) / 60);
if (minutes) {
return minutes + ' minute' + numberEnding(minutes);
}
var seconds = temp % 60;
if (seconds) {
return seconds + ' second' + numberEnding(seconds);
}
return 'less than a second'; //'just now' //or other string you like;
}
eg: usage
var str = dateToStr('2014-10-05 15:22:16');
There is the Intl.RelativeTimeFormat API, which is supported in recent versions of Chrome and Firefox.
An few examples:
let rtf = new Intl.RelativeTimeFormat("en");
rtf.format(-1, "day"); // 'yesterday'
rtf.format(-2, 'day'); // '2 days ago'
rtf.format(13.37, 'second'); // 'in 13.37 seconds'
And there's a lot more in this blog post and in the proposal itself.
To show only what you need and not day 0, hours 0...
formatTime = function(time) {
var ret = time % 1000 + ' ms';
time = Math.floor(time / 1000);
if (time !== 0) {
ret = time % 60 + "s "+ret;
time = Math.floor(time / 60);
if (time !== 0) {
ret = time % 60 + "min "+ret;
time = Math.floor(time / 60);
if (time !== 0) {
ret = time % 60 + "h "+ret;
...
}
}
}
return ret;
};
Following a similar approach to #Dan, I have modified #Royi Namir's code to output a string with commas and and's:
secondsToString = function(seconds) {
var numdays, numhours, nummilli, numminutes, numseconds, numyears, res;
numyears = Math.floor(seconds / 31536000);
numdays = Math.floor(seconds % 31536000 / 86400);
numhours = Math.floor(seconds % 31536000 % 86400 / 3600);
numminutes = Math.floor(seconds % 31536000 % 86400 % 3600 / 60);
numseconds = seconds % 31536000 % 86400 % 3600 % 60;
nummilli = seconds % 1.0;
res = [];
if (numyears > 0) {
res.push(numyears + " years");
}
if (numdays > 0) {
res.push(numdays + " days");
}
if (numhours > 0) {
res.push(numhours + " hours");
}
if (numminutes > 0) {
res.push(numminutes + " minutes");
}
if (numseconds > 0) {
res.push(numseconds + " seconds");
}
if (nummilli > 0) {
res.push(nummilli + " milliseconds");
}
return [res.slice(0, -1).join(", "), res.slice(-1)[0]].join(res.length > 1 ? " and " : "");
};
It has no period so one can add sentences after it, like here:
perform: function(msg, custom, conn) {
var remTimeLoop;
remTimeLoop = function(time) {
if (time !== +custom[0]) {
msg.reply((secondsToString(time)) + " remaining!");
}
if (time > 15) {
return setTimeout((function() {
return remTimeLoop(time / 2);
}), time / 2);
}
};
// ...
remTimeLoop(+custom[0]);
}
Where custom[0] is the total time to wait for; it will keep dividing the time by 2, warning the time remaining until the timer ends, and stop warning once the time is under 15 seconds.
Below will work for both past and future datetime, also have option to pass locale.
function relativeTime(isoString, locale = "en") {
const timestamp = Date.parse(isoString);
const msPerMinute = 60 * 1000;
const msPerHour = msPerMinute * 60;
const msPerDay = msPerHour * 24;
const msPerMonth = msPerDay * 30;
const msPerYear = msPerDay * 365;
const current = Date.now();
let elapsed = current - timestamp;
const sign = elapsed > 0 ? -1 : 1;
elapsed = Math.abs(elapsed);
const rtf = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
if (elapsed < msPerMinute) {
return rtf.format(sign * Math.floor(elapsed / 1000), "seconds");
} else if (elapsed < msPerHour) {
return rtf.format(sign * Math.floor(elapsed / msPerMinute), "minutes");
} else if (elapsed < msPerDay) {
return rtf.format(sign * Math.floor(elapsed / msPerHour), "hours");
} else if (elapsed < msPerMonth) {
return rtf.format(sign * Math.floor(elapsed / msPerDay), "days");
} else if (elapsed < msPerYear) {
return rtf.format(sign * Math.floor(elapsed / msPerMonth), "months");
} else {
return new Date(timestamp).toLocaleString(locale);
}
}
Output:
relativeTime(new Date().toISOString()) //'2021-11-13T18:48:58.243Z'
-> now
relativeTime('2021-11-13T18:48:50.243Z')
-> 8 seconds ago
relativeTime('2021-11-14T18:48:50.243Z')
-> in 23 hours
relativeTime('2021-11-15T18:48:50.243Z')
-> tomorrow
relativeTime('2021-10-15T18:48:50.243Z')
-> 29 days ago
relativeTime('2021-12-15T18:48:50.243Z')
-> next month
This is a solution. Later you can split by ":" and take the values of the array
/**
* Converts milliseconds to human readeable language separated by ":"
* Example: 190980000 --> 2:05:3 --> 2days 5hours 3min
*/
function dhm(t){
var cd = 24 * 60 * 60 * 1000,
ch = 60 * 60 * 1000,
d = Math.floor(t / cd),
h = '0' + Math.floor( (t - d * cd) / ch),
m = '0' + Math.round( (t - d * cd - h * ch) / 60000);
return [d, h.substr(-2), m.substr(-2)].join(':');
}
//Example
var delay = 190980000;
var fullTime = dhm(delay);
console.log(fullTime);
I'm a big fan of objects, so I created this from https://metacpan.org/pod/Time::Seconds
Usage:
var human_readable = new TimeSeconds(986543).pretty(); // 11 days, 10 hours, 2 minutes, 23 seconds
;(function(w) {
var interval = {
second: 1,
minute: 60,
hour: 3600,
day: 86400,
week: 604800,
month: 2629744, // year / 12
year: 31556930 // 365.24225 days
};
var TimeSeconds = function(seconds) { this.val = seconds; };
TimeSeconds.prototype.seconds = function() { return parseInt(this.val); };
TimeSeconds.prototype.minutes = function() { return parseInt(this.val / interval.minute); };
TimeSeconds.prototype.hours = function() { return parseInt(this.val / interval.hour); };
TimeSeconds.prototype.days = function() { return parseInt(this.val / interval.day); };
TimeSeconds.prototype.weeks = function() { return parseInt(this.val / interval.week); };
TimeSeconds.prototype.months = function() { return parseInt(this.val / interval.month); };
TimeSeconds.prototype.years = function() { return parseInt(this.val / interval.year); };
TimeSeconds.prototype.pretty = function(chunks) {
var val = this.val;
var str = [];
if(!chunks) chunks = ['day', 'hour', 'minute', 'second'];
while(chunks.length) {
var i = chunks.shift();
var x = parseInt(val / interval[i]);
if(!x && chunks.length) continue;
val -= interval[i] * x;
str.push(x + ' ' + (x == 1 ? i : i + 's'));
}
return str.join(', ').replace(/^-/, 'minus ');
};
w.TimeSeconds = TimeSeconds;
})(window);
I cleaned up one of the other answers a bit provides nice '10 seconds ago' style strings:
function msago (ms) {
function suffix (number) { return ((number > 1) ? 's' : '') + ' ago'; }
var temp = ms / 1000;
var years = Math.floor(temp / 31536000);
if (years) return years + ' year' + suffix(years);
var days = Math.floor((temp %= 31536000) / 86400);
if (days) return days + ' day' + suffix(days);
var hours = Math.floor((temp %= 86400) / 3600);
if (hours) return hours + ' hour' + suffix(hours);
var minutes = Math.floor((temp %= 3600) / 60);
if (minutes) return minutes + ' minute' + suffix(minutes);
var seconds = Math.floor(temp % 60);
if (seconds) return seconds + ' second' + suffix(seconds);
return 'less then a second ago';
};
function java_seconds_to_readable(seconds)
{
var numhours = Math.floor(seconds / 3600);
var numminutes = Math.floor((seconds / 60) % 60);
var numseconds = seconds % 60;
return numhours + ":" + numminutes + ":" + numseconds;
}
More simple way. You can years and days respectively.
if you use node :
const humanize = require('human-date');
let yesterday = new Date(new Date().setDate(new Date().getDate()-1));
console.log(humanize.relativeTime(yesterday)); //=> 1 day ago
function secondsToTimeString(input) {
let years = 0, days = 0, hours = 0, minutes = 0, seconds = 0;
let ref = [31536000,86400,3600,60,1];
for (let i = 0;i < ref.length;i++) {
let val = ref[i];
while (val <= input) {
input -= val;
if (i === 0) years++;
if (i === 1) days++;
if (i === 2) hours++;
if (i === 3) minutes++;
if (i === 4) seconds++;
}
return {years, days, hours, minutes, seconds};
}

Categories