I am making a notification system which require the time since functionality.
I am using this script for timesince function(jQuery):
$.fn.updateSince = function(interval) {
var times = this.map(function(){ return { e: $(this), t: parseInt($(this).html()) }; });
var format = function(t) {
if(t > 86400) {
return Math.floor(t / 86400) + ' days ago';
} else if (t > 3600) {
return Math.floor(t / 3600) + ' hours ago';
} else if (t > 60) {
return Math.floor(t / 60) + ' minute ago';
} else if (t > 50) {
return '50 seconds ago';
} else if (t > 40) {
return '40 seconds ago';
} else if (t > 30) {
return '30 seconds ago';
} else if (t > 25) {
return '25 seconds ago';
} else if (t > 15) {
return '15 seconds ago';
} else if (t > 10) {
return '10 seconds ago';
} else {
return 'a few seconds ago';
}
}
var update = function(){
var now = new Date().getTime();
$.each(times, function(i, o){
o.e.html(format(Math.round((now - o.t) / 1000)));
});
};
window.setInterval(update, interval);
update();
return this;
}
The notifications are stored in MySQL database , each notification has a timestamp on it that is in this format: 2012-12-26 06:21:28
I use PHP strtotime and change it into UTC format when obtaining the time out of the database for each notificaiton item:(php)
$rows['time']= strtotime($temp_time." UTC");
When I pass it back to the client browser , using ajax. I will multiply the UTC time(from database) with 1000(javascript)
var time = parseInt(dbtime * 1000);
Then I can use the jQuery timesince function to turn it into time ago.
Problem:
My server time varies with client browser time.
How do I make them “compatible” with each other.
For example , a notification is made 2 hours ago according to client browser.
But PHP says its made 7 hours ago.
because client browser timezone is different with my server’s
My logic is:
1. [PHP] Get current time , and use the notification time obtained from database to subtract with it.
database time – current time = time difference on server end
- [PHP] Then we get a time difference. in this case 7 hours.
- [PHP] How do i turn 7 hours into UTC format?
- [Javascript] Send the current client browser time , also in UTC format to php script.
- [PHP] client browser time – 7 hours(UTC?) = actual time of notification created for javascript use.
- [PHP] Send back the results to Javascript , so now the time can be 2 hours ago on client browser’s end.
How do I do this?
Just for info , UTC format is like(multiplied with 1000) : 1314952284779
Your logic could be:
strtotime(or any similar function)Datefunction with this value (multiplied by 1000) to re-build the dateThe problem I see here is in the first step. You mention that the dates are stored as
2012-12-26 06:21:28but what timezone does this date correspond to? If it is the same time as the server timezone then usingstrtotime("2012-12-26 06:21:28")is sufficient to generate correct timestamp.