I am trying to get the events for any date that a user clicks on the calendar.
When you click a date, say 8/15, the date is sent to the server as a string (yyyy-mm-dd) via ajax and updates a div on the page with events for that date:
$.ajax({
type: "GET",
url: "{% url 'update-home' %}",
data: {'send_date': send_date},
success: function(response) {
console.log(response)
$('#events').show().fadeOut(50, function() {
$('#events').html(response).fadeIn(50);
});
},
error: function(rs, e) {
alert('Something went wrong.');
}
});
This works correctly. I am pulling events from the server like so:
def update_home_ajax(request):
the_date = request.GET['send_date']
events = Event.objects.filter(start_time__startswith=the_date).filter(is_private=False).filter(is_deleted=False).exclude(event_type="convention").order_by("-created_date")
This works in the sense that it pulls all the events on the date the user is clicking. However, the problem I have is that the events being pulled are saved in UTC. The incorrect queryset occurs if a user in EST clicks 8/16 at 01:00 (1am) for example, then the event is actually being returned as 21:00 on 8/15 so it is not filtering accurately.
I have tried converting the queryset to the users timezone, but then I will still miss some events when I first pull them from the DB.
I do not have trouble converting to a user's timezone on the website. Only when I try to update the div of events based on the date that the user clicks, which is sent to the server to update the events.
How can I make sure that I am pulling events from the DB that accurately reflect the intended date if I store as UTC and each user has a specified timezone?
The date you send to the server needs to include the timezone it's from, so that your server can correctly convert it to a time range in UTC and use that range to query the database. Either that, or you convert the date to UTC before you send it to the server - in this case you'd probably end up sending a start and end datetime to the server, because, for example, the 24hr period known as 15th August EST spans across parts of 2 days when converted UTC, so a simple single date isn't enough to describe the time range required.
It doesn't really matter which way round you do it I don't think - either convert it before you send it, or afterwards. As long as the server knows what to expect then it would work.