2

I am having trouble adding in a year to my count up code.

I have tried this:

days=Math.floor(difference/(60*60*1000*24)*1);
days=Math.floor(difference/(60*60*1000*24)*1/365);
hours=Math.floor((difference%(60*60*1000*24))/(60*60*1000)*1/365);
mins=Math.floor(((difference%(60*60*1000*24))%(60*60*1000))/(60*1000)*1/365);
secs=Math.floor((((difference%(60*60*1000*24))%(60*60*1000))%(60*1000))/1000*1/365);

document.getElementById('countup').setAttribute("uptime",years+':'days+':'+hours+':'+mins+':'+secs)
document.getElementById('years').firstChild.nodeValue = years;
document.getElementById('days').firstChild.nodeValue = days;
document.getElementById('hours').firstChild.nodeValue = hours;
document.getElementById('minutes').firstChild.nodeValue = mins;
document.getElementById('seconds').firstChild.nodeValue = secs;

But it still didn't work. Also how would I allow for a leap year?

Working fiddle without year below:

https://jsfiddle.net/ma9ic/3jxm4e7t/

Can someone point me in the right direction. Is there an easier method for creating the same effect with jQuery?

5
  • 3
    I would recommend using a library like Moment.js rather than trying to reinvent the wheel. Otherwise, the calculation you'd need will be way more complicated than what you have so far. Commented Jun 5, 2015 at 13:46
  • 3
    jQuery is a DOM manipulation library so it's of absolutely no help for manipulating dates. Commented Jun 5, 2015 at 13:48
  • take a look, i edit your fiddle: jsfiddle.net/3jxm4e7t/1 Commented Jun 5, 2015 at 13:56
  • That's cool @Frogmouth, although I think what OP is asking for is about accurately calculating the time between two dates (Years, Months, Days, Hours, and Seconds) whilst accounting for leap years/seconds. Commented Jun 5, 2015 at 13:58
  • @Frogmouth No worries. I do like what you did though. Commented Jun 5, 2015 at 14:23

1 Answer 1

1

I think you're going to have a rough time trying to create this in plain JS and jQuery isn't really an appropriate option as it's primarily a DOM manipulation library.

Instead, I recommend using Moment.js.

It's a library dedicated to this sort of thing and handles things which you probably weren't even thinking about (like Timezones).

Just browse through the code and see what I mean.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.