Related
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)
}
I am trying to take a string in the form of '018-09-06T15:06:44.091Z' and then subtract Date.now() from it and then convert it into a days, hours, minutes, or seconds ago string. For example, I get the string above and then: var date = Date.now() - new Date('018-09-06T15:06:44.091Z'). That gives me a number: 697850577. I need to convert that number into a string that reads '3 days ago', or '30 seconds ago', based on how much time has lapsed since '018-09-06T15:06:44.091Z'. I cannot use moment.js or any other libraries. I can only use Angular.JS 1.7 and/or vanilla JS.
Current implementation works, but there has to be a better way than this:
function conversions() {
notif.rollupList.rollups.forEach(function (rollup) {
rollup.type = getChangeType(rollup.type);
rollup.modifiedAt = convertDate(rollup.modifiedAt)
})
}
// Converts the date to 'something something ago'
function convertDate(dateString) {
var seconds = Math.floor((Date.now() - new Date(dateString)) /
1000);
if (seconds >= 60) {
var minutes = Math.floor(seconds / 60);
if (minutes >= 60) {
var hours = Math.floor(minutes / 60);
if (hours >= 24) {
var days = Math.floor(hours / 24);
if (days > 1) {
return days.toString() + ' days ago'
} else {
return days.toString() + ' day ago'
}
} else {
if (hours > 1) {
return hours.toString() + ' hours ago'
} else {
return hours.toString() + ' hour ago'
}
}
} else {
if (minutes > 1) {
return minutes.toString() + ' minutes ago'
} else {
return minutes.toString() + ' minute ago'
}
}
} else {
if (second > 1) {
return seconds.toString() + ' seconds ago'
} else {
return seconds.toString() + ' second ago'
}
}
}
Thanks in advance for any help.
timeSince=(date)=>{
let seconds = Math.floor((new Date() - date) / 1000);
let interval = Math.floor(seconds / 31536000);
if (interval > 1) {
return interval + " years";
}
interval = Math.floor(seconds / 2592000);
if (interval > 1) {
return interval + " months";
}
interval = Math.floor(seconds / 86400);
if (interval > 1) {
return interval + " days";
}
interval = Math.floor(seconds / 3600);
if (interval > 1) {
return interval + " hours";
}
interval = Math.floor(seconds / 60);
if (interval > 1) {
return interval + " minutes";
}
return Math.floor(seconds) + " seconds";
}
let aDay = 24*60*60*1000
console.log(timeSince(new Date(Date.now()-aDay)));
console.log(timeSince(new Date(Date.now()-aDay*2)));
It took 1 quick google search and a quick JS fiddle test sesh cause I like ES6, to find an answer. Whether it's the right one or as efficient as you're looking for is up to you. The original post --> How to format time since xxx e.g. “4 minutes ago” similar to Stack Exchange sites <--
Looking up answers is part of being a developer, and a fun one. Do your research :)
self.calcMessageAge = function calcMessageAge(fireDate){
var date = Date.parse(fireDate);
var now = new Date();
now = Date.now();
// in seconds
var diff = Math.abs(date - now)/1000;
if(diff < 60) {
return "1 min";
}else if(diff < (60*60) ) {
// minutes
return Math.floor(diff/60) + " mins";
} else if(diff < (60*60*24)) {
// hours
var hrs = Math.floor(diff/60/60) + " hours";
if(hrs !== "1 hours") {
return Math.floor(diff/60/60) + " hours";
} else {
return Math.floor(diff/60/60) + " hour";
}
} else if(diff < (60*60*24*7)) {
// days
var _day = Math.floor(diff/24/60/60) + " days";
if(_day !== "1 days") {
return Math.floor(diff/24/60/60) + " days";
} else {
return Math.floor(diff/24/60/60) + " day";
}
} else if(diff < (60*60*24*7*4)) {
// weeks
var _weeks = Math.floor(diff/7/24/60/60) + " weeks";
if(_weeks !== "1 weeks") {
return Math.floor(diff/7/24/60/60) + " weeks";
} else {
return Math.floor(diff/7/24/60/60) + " week";
}
} else {
var _months = Math.floor(diff/4/7/24/60/60) + " months";
if(_months !== "1 months") {
return Math.floor(diff/4/7/24/60/60) + " months";
} else {
return Math.floor(diff/4/7/24/60/60) + " month";
}
}
};
The Above method should return a string based on the time (fireDate) that a notification reached the UI.
String such as "1 min ago" or "1 day ago" then "2 mins ago" or "2 days ago"
I am receiving "1 min ago" correctly but at 60 seconds I get "1 mins" returned, This also happens with day(s).
Im thinking it has to do with the fact Im checking against 60seconds when it should be 59? Im really kinda stumped. Any help would be appreciated.
You can do it like this
const getDiffrence = fireDate => {
const date = new Date(fireDate).getTime();
let now = new Date().getTime();
const diff = Math.abs(date - now) / 1000
const min = Math.floor(diff/60) % 60 || ''
const h = Math.floor(diff/60/60) % 60 || ''
const day = Math.floor(diff/60/60/24) % 24 || ''
const week = Math.floor(diff/60/60/24/7)|| ''
const month = Math.floor(diff/4/7/24/60/60) || ''
return `${month ? month + 'months' : ''} ${week ? week + 'weeks' : ''} ${day ? day + 'days' : ''} ${day ? day + 'days' : ''} ${h ? h + 'hours' : ''} ${min ? min + 'mins' : ''} `.replace(/\b(1\D+?)s/g, '$1').trim()
}
console.log(getDiffrence('2017/02/27 18:22'))
console.log(getDiffrence(new Date().getTime() - 60 * 1000 - 5000))
The main part of this code is .replace(/\b(1\D+?)s/g, '$1')
this will replace all 1 anythings with 1 anything or evnen crazer at this after it .replace(/(0\D+?)s\s*/g, '') and you just have to create string like '1days 0hours 0minutes'
console.log('11mounths 1days 0hours 20minutes'.replace(/\b0\D+?s\s*/g, '').replace(/\b(1\D+?)s/g, '$1'))
var calcMessageAge = function(fireDate) {
var date = Date.parse(fireDate);
var now = Date.now();
// in seconds
var diff = Math.abs(date - now) / 1000;
var minute = 60;
var hour = 60 * minute;
var day = 24 * hour;
var week = 7 * day;
var month = 4 * week; // month is usually longer than 4 weeks but I let the same as in original code
var num;
var label;
if (diff > month) {
num = Math.floor(diff / month);
label = num + ' month' + (num > 1 ? 's': '');
} else if (diff > week) {
num = Math.floor(diff / week);
label = num + ' week' + (num > 1 ? 's': '');
} else if (diff > day) {
num = Math.floor(diff / day);
label = num + ' day' + (num > 1 ? 's': '');
} else if (diff > hour) {
num = Math.floor(diff / hour);
label = num + ' hour' + (num > 1 ? 's': '');
} else if (diff > minute) {
num = Math.floor(diff / minute);
label = num + ' min' + (num > 1 ? 's': '');
} else {
label = '1 min';
}
return label;
};
console.log(calcMessageAge('02-02-2017'));
console.log(calcMessageAge('01-01-2017 20:00'));
console.log(calcMessageAge(new Date(new Date().getTime() - 60 * 1000)));
console.log(calcMessageAge(new Date(new Date().getTime() - 59 * 1000)));
console.log(calcMessageAge(new Date(new Date().getTime() - 60 * 60 * 4 * 1000)));
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 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};
}