How to convert time values ​​inside jinja code to the local time zone of the browser when the page loads?

I have a list of flag values ​​generated in this format: YYYY-DD-MM hh: mm: ss. These time values ​​work like url links and are displayed in my html file using jinja2 as follows:

{% for job in jobs%}
    <a href="{{ url_for('jobs/by_id',job_id=job.job_id) }►""
    {{job.finishtime}} #this is the time value
    </a>
{% endfor%}

I want these time values ​​to be automatically converted to the local time zone of the browser. I tried to use the flash moments extension, but after all the instructions and use, the {{ moment(job.finishtime).format('MMMM Do YYYY, h:mm:ss a') }}time disappears from the html page when loading. I also tried other time functions, but keep getting errors.

Is there a better way to get time.js to talk to my jinja code?

I was hoping not to deal with python datetime.

+4
source share
1 answer

, Jinja2 , - () .
, Javascript Jinja2, JS jinja2.

/ :

1) ( , ), javascript cookie timezone. - - :

# On the server
def view_jobs_page(request, response):
    import datetime
    tz = datetime.timedelta(seconds = int(request.cookies["timezone"])) # Pass this into the Jinja2 render function
    # ... Do stuff


# In your template
local time: {{ job.finishtime + tz }}

, , . datetime, .

2) javascript timedelta:

<!-- In the head -->
<script>
// When the page loads - the Jinja template is already rendered now
window.onload = function() {
  // Get all the elements with the given class, and map through them
  document.querySelectorAll(".datetime_to_be_adjusted").map(function(el){
    var utcTime = moment.utc(el.innerText);  // This is the time in UTC
    utcTime.local();  // Switch to using the browser local timezone
    el.innerText = utcTime.format('MMMM Do YYYY, h:mm:ss a');  // Write the local time back to the element
  });
}
</script>
...
{% for job in jobs %}
    <a href="{{ url_for(‘jobs/by_id’,job_id=job.job_id) }}" class="datetime_to_be_adjusted">
        {{ job.finishtime }}
    </a>
{% endfor %}

, , jJ UTC.

0

Source: https://habr.com/ru/post/1607579/


All Articles