I've been trying to figure this out for the past few days but only losing my hair over it.
I'm using the javascript below for a timer that counts up using a timestamp as the start date. I'm using a timestamp from the database, which is saved at the very moment that the timer is started, because that timestamp is saved relative to the user's timezone, which is selected in their profile.
My server php timezone is set to 'America/Los_Angeles'. My user profile timezone is also set to that. That is also the format in which the timezone is saved.
However when I run the timer, even though my php displays the correct saved time based on the saved timezone, ie. '05/29/2013 6:05:49', the timer has additional hours from the get-go. So it would look like "0 days 12 hours 0 mins 13 secs" instead of "0 days 0 hours 0 mins 13 secs".
This must be due to the javascript timezone??, since if I set my TZ to 'America/New_York' for instance, it would be "0 days 9 hours 0 mins 13 secs", correct?
How would I fix this?
JS
<script type="text/javascript">
function DaysHMSCounter(initDate, id){
this.counterDate = new Date(initDate);
this.container = document.getElementById(id);
this.update();
}
DaysHMSCounter.prototype.calculateUnit=function(secDiff, unitSeconds){
var tmp = Math.abs((tmp = secDiff/unitSeconds)) < 1? 0 : tmp;
return Math.abs(tmp < 0 ? Math.ceil(tmp) : Math.floor(tmp));
}
DaysHMSCounter.prototype.calculate=function(){
var secDiff = Math.abs(Math.round(((new Date()) - this.counterDate)/1000));
this.days = this.calculateUnit(secDiff,86400);
this.hours = this.calculateUnit((secDiff-(this.days*86400)),3600);
this.mins = this.calculateUnit((secDiff-(this.days*86400)-(this.hours*3600)),60);
this.secs = this.calculateUnit((secDiff-(this.days*86400)-(this.hours*3600)-(this.mins*60)),1);
}
DaysHMSCounter.prototype.update=function(){
this.calculate();
this.container.innerHTML =
" <strong>" + this.days + "</strong> " + (this.days == 1? "day" : "days") +
" <strong>" + this.hours + "</strong> " + (this.hours == 1? "hour" : "hours") +
" <strong>" + this.mins + "</strong> " + (this.mins == 1? "min" : "mins") +
" <strong>" + this.secs + "</strong> " + (this.secs == 1? "sec" : "secs");
var self = this;
setTimeout(function(){self.update();}, (1000));
}
window.onload=function(){ new DaysHMSCounter('05/29/2013 6:05:49', 'timer'); }
</script>
HTML
<div id="timer"></div>