Omer
Omer

Reputation: 39

How to covert django created_at/date_joined time to current user time?

I am getting the user object using

user = User.objects.all()
context = {'user':user}

Passing it to context then using in templates

{% for i in user %}

<h1>{{i.first_name}}<h1>

<h1>{{i.date_joined}}</h1>

{% endfor %}

Right now i am getting server time but i want to get the time as per the current user country time? How it can be possible?

Upvotes: 0

Views: 97

Answers (2)

Omer
Omer

Reputation: 39

I have found a way to get the user's local time and render it in the template without modifying anything in the User model.

Javascript: Store timezone in landing page cookie

const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
document.cookie = "timeZone="+timeZone;

In views.py pass it to the session to maintain the cookie server side (In the template view or in the index view)

request.session['timeZone'] = request.COOKIES.get('timeZone')

In template views.py

context['timeZone'] = request.session['timeZone']

In template.html

{% load tz ‰}

<h1>{user.date_joined|timezone:timeZone}</h1>

Upvotes: 0

Beikeni
Beikeni

Reputation: 900

The correct approach for this is to store each user's timezone in the User model or in some other model that is easily reachable. Then you can write a model method on the user that takes the server time and converts it into the user's local time. Then in your template you can simply call the method and format it as you like:

{% for user in users %}

    <h1>{{ user.date_joined_local|date:"d/m/Y H:i" }}</h1>

{% endfor %}

Upvotes: 1

Related Questions