Hey I implemented a very bad solution to get around the datetime issue I was having inorder to save posts and show posts according to user timezone (because the server timing was set to UTC) but I was hoping if someone could help me get a cleaner, more concise way of doing the same thing.
I have written down comments in the code but here the summary. The user fills in the publication date and time of the post and sets his timezone in the frontend. Since server is in UTC and suppose the user is from UTC+5, even if the user sets his current time the post will be published 5 hours later. So I Subtract the publication date with the difference of user local time and server time.
Here is the code
request.POST["datetime] from frontend form filed by the user as a publication date
Used string operation to get things like day, month year, hour, and min
dateandtime = request.POST["datetime"].split("-")
year = dateandtime[0]
month = dateandtime[1]
day = dateandtime[2][:2]
time = dateandtime[2][3:].split(":")
hour = time[0]
min = time[1]
dateandtime = datetime(
int(year), int(month), int(day), int(hour), int(min), 0
)
The user also fills in the timezone so I can get the timezone from request.POST["timezone]
timezone_user = request.POST["timezone"]
timezone.activate(timezone_user)
local_time = datetime( # get me the local time of the user
int(timezone.localtime().year),
int(timezone.localtime().month),
int(timezone.localtime().day),
int(timezone.localtime().hour),
int(timezone.localtime().minute),
int(float(timezone.localtime().second)),
)
server_time = datetime( # gives me the server time
int(timezone.now().year),
int(timezone.now().month),
int(timezone.now().day),
int(timezone.now().hour),
int(timezone.now().minute),
int(float(timezone.now().second)),
)
pub date is saved by subtracting the publication date and time set by the user
with difference between the local time of the user and the server
so if a user is in UTC+5 and the server is in UTC. the code will subtract 5 hours from the publication time to bring the post to the server time.
question = Question(
anonymous_user=anonymous_user, # storing anonymous user as foreign key
question_text=request.POST["question_text"], # storing question
pub_date=dateandtime
- (local_time - server_time), # saving publishing date
)
I know the code and solution are very ugly and that's exactly why I need this community's help to improve it. Thanks in advance. Cheers.