What you want is a function that converts the difference in (mili) seconds into something like
5d 4h 3m 2s
If you don't mind a lot of days for time periods> several months, you can use something like this:
function human_time_difference(diff) { var s = diff % 60; diff = Math.floor(diff / 60); var min = diff % 60; diff = Math.floor(diff / 60); var hr = diff % 24; diff = Math.floor(diff / 24); var days = diff; return days + 'd ' + hr + 'h ' + min + 'm ' + s + 's'; }
If you have a difference in milliseconds, you will need to pass this number divided by 1000. You can also use Math.round to get rid of fractions, but you can just leave them if you want the displayed information.
Getting months and years is a little harder for several reasons:
- The number of days in a month varies.
- When you go from the middle of the month to the middle of the next, the time interval does not apply to whole months, even if the number of days is> 31 (for example, how many months exist between June 2 and July 30?).
If you really want the number of months between two moments, the number of seconds between them is not enough. You must use calendar logic that requires passing at the beginning and at the end of a date + time.
PS: When you submit a question, avoid unnecessary details. For example, your question is not related to cookies, setInterval or onload. The only part you donโt know is how to convert (mili) seconds into several days, hours, etc. It might be useful to indicate why you are trying to do something, but if it is not important for understanding the main question, put it at the end so that people do not have to get through it before they get to the main part. The same recommendations apply to your name; make sure itโs relevant by excluding irrelevant data (e.g. cookies and countdown).
source share