Related
Well my code should be working but it isn't. Each time I reload the time, my Countdown start back at his initialised value.
Since I'm not familliar with JS you may be able to m'éclaircir the mind
<script>
var upgradeTime = 172801;
var seconds = upgradeTime;
function timer() {
var days = Math.floor(seconds/24/60/60);
var hoursLeft = Math.floor((seconds) - (days*86400));
var hours = Math.floor(hoursLeft/3600);
var minutesLeft = Math.floor((hoursLeft) - (hours*3600));
var minutes = Math.floor(minutesLeft/60);
var remainingSeconds = seconds % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('countdown').innerHTML = pad(days) + ":" + pad(hours) + ":" + pad(minutes) + ":" + pad(remainingSeconds);
if (seconds == 0) {
clearInterval(countdownTimer);
document.getElementById('countdown').innerHTML = "Completed";
} else {
seconds--;
}
}
var countdownTimer = setInterval('timer()',1000,function() {
secondPassed();
if (seconds === 0) {
eraseCookie(seconds);
} else {
createCookie(seconds, seconds, 7);
}
});
</script>
How do I call it
<h1>Server Release in : <span id="countdown" class="timer"></span></h1>
I just want my timer to not refresh each time you reload the page.
Any kind of help would be appreciated
Here you go.
var upgradeTime = 172801; //Timer length in ms
var timerMS = window.localStorage.getItem("date");
startTimer();
function timer() {
var difference = timerMS - Date.now();
if (difference <= 0) {
startTimer();
return;
}
var seconds = (difference / 1000).toFixed(0),
days = Math.floor(seconds / 24 / 60 / 60),
hoursLeft = Math.floor((seconds) - (days * 86400)),
hours = Math.floor(hoursLeft / 3600),
minutesLeft = Math.floor((hoursLeft) - (hours * 3600)),
minutes = Math.floor(minutesLeft / 60),
remainingSeconds = seconds % 60;
function pad(n) {
return (n < 10 ? "0" + n : n);
}
document.getElementById('countdown').innerHTML = pad(days) + ":" + pad(hours) + ":" + pad(minutes) + ":" + pad(remainingSeconds);
setTimeout(timer, 1000);
}
function startTimer() {
if (!timerMS || timerMS < Date.now()) {
timerMS = Date.now() + upgradeTime;
window.localStorage.setItem("date", timerMS);
}
timer();
}
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())
I have a Javascript timing event with an infinite loop with a stop button.
It will display numbers when start button is click.Now I want this numbers converted to something like 4 hours, 3 minutes , 50 seconds
var c = 0;
var t;
var timer_is_on = 0;
function timedCount() {
document.getElementById('txt').value = c;
c = c + 1;
t = setTimeout(function() {
timedCount()
}, 1000);
}
function doTimer() {
if (!timer_is_on) {
timer_is_on = 1;
timedCount();
}
}
function stopCount() {
clearTimeout(t);
timer_is_on = 0;
}
$(".start").on("click", function() {
//var start = $.now();
//alert(start);
//console.log(start);
doTimer();
$(".end").show();
$(".hide_div").show();
});
$(".end").on("click", function() {
stopCount();
});
.hide_div {
display: none;
}
.end {
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p class="start">Start</p>
<p class="end">End</p>
<p class="hide_div">
<input type="text" id="txt" />//display numbers eg 12345
</p>
How to convert numbers like 123456 to 1 day, 4 hours, 40 min, 45 seconds?
I suggest doing this way!:
function secondsToDhms(seconds) {
seconds = Number(seconds);
var d = Math.floor(seconds / (3600*24));
var h = Math.floor(seconds % (3600*24) / 3600);
var m = Math.floor(seconds % 3600 / 60);
var s = Math.floor(seconds % 60);
var dDisplay = d > 0 ? d + (d == 1 ? " day, " : " days, ") : "";
var hDisplay = h > 0 ? h + (h == 1 ? " hour, " : " hours, ") : "";
var mDisplay = m > 0 ? m + (m == 1 ? " minute, " : " minutes, ") : "";
var sDisplay = s > 0 ? s + (s == 1 ? " second" : " seconds") : "";
return dDisplay + hDisplay + mDisplay + sDisplay;
}
Use Math like this way, Second param in parseInt is for base, which is optional
var seconds = parseInt(123456, 10);
var days = Math.floor(seconds / (3600*24));
seconds -= days*3600*24;
var hrs = Math.floor(seconds / 3600);
seconds -= hrs*3600;
var mnts = Math.floor(seconds / 60);
seconds -= mnts*60;
console.log(days+" days, "+hrs+" Hrs, "+mnts+" Minutes, "+seconds+" Seconds");
Your given seconds 123456 would be 1 days, 10 Hrs, 17 Minutes, 36 Seconds not 1 days, 4 Hrs, 40 Minutes, 45 Seconds
function countdown(s) {
const d = Math.floor(s / (3600 * 24));
s -= d * 3600 * 24;
const h = Math.floor(s / 3600);
s -= h * 3600;
const m = Math.floor(s / 60);
s -= m * 60;
const tmp = [];
(d) && tmp.push(d + 'd');
(d || h) && tmp.push(h + 'h');
(d || h || m) && tmp.push(m + 'm');
tmp.push(s + 's');
return tmp.join(' ');
}
// countdown(3546544) -> 41d 1h 9m 4s
// countdown(436654) -> 5d 1h 17m 34s
// countdown(3601) -> 1h 0m 1s
// countdown(121) -> 2m 1s
My solution with map() and reduce():
const intervalToLevels = (interval, levels) => {
const cbFun = (d, c) => {
let bb = d[1] % c[0],
aa = (d[1] - bb) / c[0];
aa = aa > 0 ? aa + c[1] : '';
return [d[0] + aa, bb];
};
let rslt = levels.scale.map((d, i, a) => a.slice(i).reduce((d, c) => d * c))
.map((d, i) => ([d, levels.units[i]]))
.reduce(cbFun, ['', interval]);
return rslt[0];
};
const TimeLevels = {
scale: [24, 60, 60, 1],
units: ['d ', 'h ', 'm ', 's ']
};
const secondsToString = interval => intervalToLevels(interval, TimeLevels);
If you call secondsToString(123456), you can get "1d 10h 17m 36s "
Here is my solution, a simple function that will round to the nearest second!
var returnElapsedTime = function(epoch) {
//We are assuming that the epoch is in seconds
var hours = epoch / 3600,
minutes = (hours % 1) * 60,
seconds = (minutes % 1) * 60;
return Math.floor(hours) + " hours, " + Math.floor(minutes) + " minutes, " + Math.round(seconds) + " seconds";
}
Came up with my own variation to some of the solutions suggested in this thread.
if (!Number.prototype.secondsToDHM) {
Number.prototype.secondsToDHM = function() {
const secsPerDay = 86400;
const secsPerHour = 3600;
const secsPerMinute = 60;
var seconds = Math.abs(this);
var minus = (this < 0) ? '-' : '';
var days = Math.floor(seconds / secsPerDay);
seconds = (seconds % secsPerDay);
var hours = Math.floor(seconds / secsPerHour);
seconds = (seconds % secsPerHour);
var minutes = Math.floor(seconds / secsPerMinute);
seconds = (seconds % secsPerMinute);
var sDays = new String(days).padStart(1, '0');
var sHours = new String(hours).padStart(2, '0');
var sMinutes = new String(minutes).padStart(2, '0');
return `${minus}${sDays}D ${sHours}:${sMinutes}`;
}
}
var a = new Number(50000).secondsToDHM();
var b = new Number(100000).secondsToDHM();
var c = new Number(200000).secondsToDHM();
var d = new Number(400000).secondsToDHM();
console.log(a);
console.log(b);
console.log(c);
console.log(d);
This answer builds upon on Andris' approach to this question, but it doesn't have trailing commas if lesser units are not present.
It also borrows from this answer dealing with joining array values only if truthy:
https://stackoverflow.com/a/19903063
I'm not a javascript god and it's probably horribly over-engineered, but hopefully readable and correct!
function sformat(s) {
// create array of day, hour, minute and second values
var fm = [
Math.floor(s / (3600 * 24)),
Math.floor(s % (3600 * 24) / 3600),
Math.floor(s % 3600 / 60),
Math.floor(s % 60)
];
// map over array
return $.map(fm, function(v, i) {
// if a truthy value
if (Boolean(v)) {
// add the relevant value suffix
if (i === 0) {
v = plural(v, "day");
} else if (i === 1) {
v = plural(v, "hour");
} else if (i === 2) {
v = plural(v, "minute");
} else if (i === 3) {
v = plural(v, "second");
}
return v;
}
}).join(', ');
}
function plural(value, unit) {
if (value === 1) {
return value + " " + unit;
} else if (value > 1) {
return value + " " + unit + "s";
}
}
console.log(sformat(60)); // 1 minute
console.log(sformat(3600)); // 1 hour
console.log(sformat(86400)); // 1 day
console.log(sformat(8991)); // 2 hours, 29 minutes, 51 seconds
If you needed to convey the duration more 'casually' in words, you could also do something like:
var remaining_duration = sformat(117);
// if a value is returned, add some prefix and suffix
if (remaining_duration !== "") {
remaining_duration = "about " + remaining_duration + " left";
}
$(".remaining_duration").text(remaining_duration);
// returns 'about 1 minute, 57 seconds left'
I further tweaked the code by Svetoslav as follows:
function convertSecondsToReadableString(seconds) {
seconds = seconds || 0;
seconds = Number(seconds);
seconds = Math.abs(seconds);
const d = Math.floor(seconds / (3600 * 24));
const h = Math.floor(seconds % (3600 * 24) / 3600);
const m = Math.floor(seconds % 3600 / 60);
const s = Math.floor(seconds % 60);
const parts = [];
if (d > 0) {
parts.push(d + ' day' + (d > 1 ? 's' : ''));
}
if (h > 0) {
parts.push(h + ' hour' + (h > 1 ? 's' : ''));
}
if (m > 0) {
parts.push(m + ' minute' + (m > 1 ? 's' : ''));
}
if (s > 0) {
parts.push(s + ' second' + (s > 1 ? 's' : ''));
}
return parts.join(', ');
}
Short answer:
var s = (Math.floor(123456/86400) + ":" + (new Date(123456 * 1000)).toISOString().substr(11, 8)).split(":");
console.log(`${s[0]} days, ${s[1]} hours, ${s[2]} minutes, ${s[3]} seconds` )
Edit:
Let me break it down in parts :
Math.floor(123456/86400)
86400 is the the total seconds in a day (60 seconds * 60 minutes * 24 hours). Dividing the inputted seconds by this value gives us number of days. We just need the whole part so we use Math.floor because the fractional piece is handled by this part:
(new Date(123456 * 1000)).toISOString().substr(11, 8)
the explanation can be found here:
Convert seconds to HH-MM-SS with JavaScript?
It just outputs hh:mm:ss, no days. So the first part and this part is a perfect combination
We concatenate using a colon (:) as a separator. The string looks like this:
'1:10:17:36'
We split it into an array with .split(":");. Then finally, we format the elements of the array for the desired output.
I've tweaked the code that Andris posted https://stackoverflow.com/users/3564943/andris
// https://stackoverflow.com/questions/36098913/convert-seconds-to-days-hours-minutes-and-seconds
function app_ste_36098913_countdown_seconds_to_hr(seconds) {
seconds = seconds || 0;
seconds = Number(seconds);
seconds = Math.abs(seconds);
var d = Math.floor(seconds / (3600*24));
var h = Math.floor(seconds % (3600*24) / 3600);
var m = Math.floor(seconds % 3600 / 60);
var s = Math.floor(seconds % 60);
var parts = new Array();
if (d > 0) {
var dDisplay = d > 0 ? d + ' ' + (d == 1 ? "day" : "days") : "";
parts.push(dDisplay);
}
if (h > 0) {
var hDisplay = h > 0 ? h + ' ' + (h == 1 ? "hour" : "hours") : "";
parts.push(hDisplay)
}
if (m > 0) {
var mDisplay = m > 0 ? m + ' ' + (m == 1 ? "minute" : "minutes") : "";
parts.push(mDisplay)
}
if (s > 0) {
var sDisplay = s > 0 ? s + ' ' + (s == 1 ? "second" : "seconds") : "";
parts.push(sDisplay)
}
return parts.join(', ', parts);
}
You will probably find using epoch timestamps more straightforward: As detailed in Convert a Unix timestamp to time in JavaScript, the basic method is like so:
<script>
// Create a new JavaScript Date object based on the timestamp
// multiplied by 1000 so that the argument is in milliseconds, not seconds.
var date1 = new Date();
alert ('easy trick to waste a few seconds...' + date1);
// var date = date2 - date1;
// Hours part from the timestamp
var hours1 = date1.getHours();
// Minutes part from the timestamp
var minutes1 = "0" + date1.getMinutes();
// Seconds part from the timestamp
var seconds1 = "0" + date1.getSeconds();
var date2 = new Date();
// Hours part from the timestamp
var hours2 = date2.getHours();
// Minutes part from the timestamp
var minutes2 = "0" + date2.getMinutes();
// Seconds part from the timestamp
var seconds2 = "0" + date2.getSeconds();
// Will display time in 10:30:23 format
// var formattedTime = hours + ':' + minutes.substr(-2) + ':' + seconds.substr(-2);
var elapsedHrs = hours2 - hours1;
var elapsedMin = minutes2.substr(-2) -minutes1.substr(-2);
var elapsedSec = seconds2.substr(-2) - seconds1.substr(-2);
var elapsedTime = elapsedHrs + ' hours, ' + elapsedMin + ' minutes, ' + elapsedSec + ' seconds';
alert ('time between timestamps: ' + elapsedTime);
</script>
Be warned that this script needs some work since for now it will give negative values for things like date1 = 12:00:00 and date2 = 12:00:05, but I'll leave that to you fo now.
You should rewrite your code to take a timestamp ( var x = new Date(); ) at the start of your timer and one whenever you are done/want to check elapsed time, and subtract the two before parsing out elapsed seconds, minutes, hours etc as required.
This is my take at the question, even if it is an old topic.
You can use a loop to compute everything for you :
function time_remaining(date1, date2) {
let seconds = (date2 - date1) / 1000
let units = ["years", "days", "h", "min", "s"]
let limit_units = [365, 24, 60, 60, 1]
const reducer = (accumulator, curr) => accumulator * curr;
let time = []
for (let i = 0; i < units.length; i++) {
let divisor = limit_units.slice(i).reduce(reducer)
let value = Math.floor(seconds / divisor)
seconds = seconds - value * divisor
time.push(value)
}
return clean_time(time, units)
}
// at this point, you have your answer. However,
// we can improve the result by removing all none
// significative null units (i.e, if your countdown is
// only about hours, minutes and seconds, it is not
// going to include years and days.)
function clean_time(time, units) {
time = time.reverse()
while (time[time.length - 1] == 0) {
time.pop()
}
return [time.reverse(), units.slice(-time.length)]
}
let date1 = Date.parse("2023-07-09T17:50:33")
console.log(time_remaining(Date.now(), date1))
I have a Javascript countdown from 12am to 9pm each day and then resets itself.
I want the countdown to go from 8am-9pm instead of 12am-9pm. I have been fiddling with this but I can't seem to make it work with a start time other than the defaulted 12am.
My question is how can I make the countdown from 8-21 hours instead of 0-21 hours?
Javascript:
if (document.getElementById('countdown')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
function countDown(){
var now = new Date();
if ( (now.getDay() >= 1) && (now.getDay() <= 7) ) { // Monday to Sunday
var target = 21; // 21:00hrs is the cut-off point
if (now.getHours() < target) { //
var hrs = (target - 1) - now.getHours();
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdown').innerHTML = str;
}
else
$('.wereOpen').hide();
}
}
var timerRunning = setInterval('countDown()', 1000);
}
Website
I don't fully understand your question, but could you just add now.getHours() >= 7 to your if statement, i.e.
...
if (now.getHours() >= 7 && now.getHours() < target) {
...
} else {
$('.wereOpen').hide();
}
...
EDIT
In light of the comment, the following should work:
if (document.getElementById('countdown')) {
pad = function(n, len) { // leading 0's
var s = n.toString();
return (new Array( (len - s.length + 1) ).join('0')) + s;
};
function countDown(){
var now = new Date();
if ( (now.getDay() >= 1) && (now.getDay() <= 7) ) { // Monday to Sunday
var target = 21; // 21:00hrs is the cut-off point
var hours = now.getHours(); //get hours
if(hours < 8 || hours >= target) {
$('.wereOpen').hide();
return;
} else
$('.wereOpen').show();
var hrs = (target - 1) - hours;
if (hrs < 0) hrs = 0;
var mins = 59 - now.getMinutes();
if (mins < 0) mins = 0;
var secs = 59 - now.getSeconds();
if (secs < 0) secs = 0;
var str = pad(hrs, 2) + ':' + pad(mins, 2) + '.<small>' + pad(secs, 2) + '</small>';
document.getElementById('countdown').innerHTML = str;
}
}
var timerRunning = setInterval('countDown()', 1000);
}
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};
}