Page 1 of 1

JS Date.getTime returning wrong value

Posted: Fri Mar 02, 2012 12:00 pm
by dave1909
I've got a javascript countdown timer for my website which is showing the wrong time

Code: Select all

function cdc(endtime,tru,pete,phptime) {
 ended = 'Round ' + tru + ' - Ended';
 	
	var d=new Date();
	var t=d.getTime();
	var t2 = t/1000;
 	var t3 = Math.floor(t2);
 	var secondsr = endtime-t3;
 	
 	if(secondsr<1){
	  	document.getElementById('clock2').innerHTML=ended; alert("Round Has Ended");
	}
	else{
		var days = Math.floor(secondsr/86400);
		var remaining = secondsr%86400;
		var hours = Math.floor(remaining/3600);
		var remaining2 = remaining%3600;
		var minutes = Math.floor(remaining2/60);
		var seconds = remaining2%60;
		var secondsr=secondsr-1;
		if(days>0){ var string1 = days + ' days,';}else{string1 = "";}
		if(hours>0){ var string2 = ' ' + hours + ' hours,';}else{string2 = "";}
		if(minutes>0){ var string3 = ' ' + minutes + ' minutes,';}else{string3 = "";}
		var string4 = ' ' + seconds + ' seconds'
		timeleft = '<nobr>Round ' + tru + ' Ends In ' + string1 + string2 + string3 + string4 + '</nobr>';
		document.getElementById('clock2').innerHTML=timeleft;
		setTimeout('cdc(' + endtime + ',' + tru + ',' + pete + ',' + phptime + ')',1000);
		
		if (pete == 'yes'){
			petestring = "PHP time is " + phptime + "<br /> Javascript time is " + t3 + "<br />Round ends at " + endtime;
			document.write(petestring);
		}
	}
}
this is returning

[text]PHP time is 1330711159
Javascript time is 1330711149
Round ends at 1330988400[/text]

any help would be greatly appreciated into helping me understand why i'm getting different times.

Thanks

Re: JS Date.getTime returning wrong value

Posted: Fri Mar 02, 2012 12:02 pm
by Celauran
PHP gets time from the server, JS from the client.

Re: JS Date.getTime returning wrong value

Posted: Fri Mar 02, 2012 12:04 pm
by dave1909
so that means my computer time is wrong?

I've synchronised my computer with windows server time and is now showing just 1 second out.

Still not accurate so i'm going to detect the difference between PHP and JS time the first time the loop is run and subsequently apply that difference to the clock