views:

744

answers:

2

I have a portion of script that calculates the days remaining to an event:

var currTime = Math.round(new Date().getTime() / 1000.0);
var dispDate = event.find('UnixEpoch').text();
var diffDate = (dispDate - currTime) / 86400;
var dateRound = Math.round(diffDate) - 30;

The first line gets the current Unix Epoch time and shaves off the milliseconds. The second line gets the future event date from an XML feed. If I put both times into an Epoch calculator online, I get the correct date for both currTime and dispDate. But when I divide them down to days (third line), the end result is off by more than 30 days, requiring that I use the last line to get the right number of days.

Now, that's strange enough. But there's something else going on that I can't figure out. It used to be off by 31 days, and now that's wrong, so I altered the script to 30 days, which is right.

Can anyone point out what I'm doing wrong? I can't for the life of me figure out why this is happening, and I'd rather not have to keep tweaking it.

+1  A: 

On the face of it the code looks OK.

Try dumping out the values of currTime and dispDate before you do the subtraction and see whether they're consistent.

The error you're reporting suggests an off-by-one error in the month portion of the code somewhere. This month is 30 days long, and last month was 31 days long. The probable location of the error is within the event.find('UnixEpoch') call.

Alnitak
I've dumped and checked both values numerous times, and they're always correct. For example, here's a date from an upcoming event I just pulled from the XML feed: 1243270800, which is GMT: Mon, 25 May 2009 17:00:00 GMT, which is correct.
b. e. hollenbeck
and what does it output if you ask for currTime? You do know it's April now, yes? ;-)
Alnitak
Alnitak
Right - you get 32 instead of 2, which would be the correct answer.
b. e. hollenbeck
umm, no. It's still 32 days until May 25th...
Alnitak
Wait a second ... !
b. e. hollenbeck
I'm still waiting... but I can't wait another 30 days... ;-)
Alnitak
It was an error in the Perl script that generated the timestamp. Problem solved!
b. e. hollenbeck
A: 

Is the event date being processed by other Javascript? If you use the new Date(year, month, day, etc...) format, month is zero based, which is easy to forget.

Justin Love
It's being created by Perl.
b. e. hollenbeck