I’m using the jQuery Coundown plugin with Django to generate accurate and synced data for every view.
For syncing time that is displayed on all browsers, I use serverSync function of the plugin to pass the data (very similar to the example) like this:
function serverTime() {
var time;
$.ajax({url: '/ajax/get-server-time/',
async: false, dataType: 'text',
success: function(text) {
time = new Date(text);
}, error: function(http, message, exc) {
time = new Date();
}});
return time;
}
And my countdown init selector function is as such (I add unixtime to data of the element for the endDatetime via Django):
function initAllTimers(selected){
$(selected).each(function(){
endDatetime = new Date($(this).attr("data-unixtime") * 1000);
$(this).countdown({until: endDatetime, serverSync: serverTime});
});
}
Django template generates each field to be filled with the coundown as such:
<span class="timeLeft" data-unixtime="1334898000"></span>
And I apply timecounting to these field like like this:
initAllTimers('.timeLeft');
And finally Django view method or generating timestamp for this plugin to retrieve (via my serverTime() method):
#points to /ajax/get-server-time/
def get_server_time(request):
now = datetime.now()
response = HttpResponse( now.isoformat())
response['Expires'] = 'Fri, 1 Jan 2010 00:00:00 GMT'
response['Content-Type'] = 'text/plain; charset=utf-8'
response['Cache-Control'] = 'no-cache, must-revalidate'
return response
It renders correctly but it’s not synced across different computers, my Mac shows a different timeleft to my windows computer.
I suspect I make a mistake at this part:
Is the php example from countdown’s example $now->format("M j, Y H:i:s O")."\n"; same to my python function datetime.now().isoformat() ?
datetime.now().isoformat()is not identical to$now->format("M j, Y H:i:s O")PHP’s formatting escapes are explained here http://php.net/manual/en/function.date.php
You can use
strftime()to properly format your timestamp in Python; the docs are available here http://docs.python.org/library/datetime.html#strftime-strptime-behavior.strftime("%b %d, %Y %H:%M:%S %z")should be near identical to the PHPformat()call; if you do not get a suitable offset from%z, you can manually add+0000yourself to the Python string.