[Django]-Django date to javascript at the template

73👍

I’ve had a lot of success with the isoformat function in python:

var selected_date = new Date("{{ selected_date.isoformat }}")

13👍

The accepted answer may generate an incorrect date depending on locale.

In FF console:

>>> n = new Date('2011-01-01');
Date {Fri Dec 31 2010 16:00:00 GMT-0800 (PST)}

It’s therefore preferable to pass Y,m,d integers to the Date constructor.

I use a template filter to generate the date constructor:

@register.filter(name='jsdate')
def jsdate(d):
    """formats a python date into a js Date() constructor.
    """
    try:
        return "new Date({0},{1},{2})".format(d.year, d.month - 1, d.day)
    except AttributeError:
        return 'undefined'
👤rych

8👍

I was using this and realized Android was returning ‘Invalid Date’ when parsing it – I think it’s stricter than the desktop Webkit. I am instead using the following, which seems to work:

new Date('{{ talk.start_datetime|date:"D, d M Y H:i:s"}}'),

More on JS date parsing is here:
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/parse

1👍

If you are using your date in JS, you will want to use the escapejs filter.

<script type="text/javascript">
    var selected_date = new Date({{ selected_date|escapejs }});
    alert(selected_date);
</script>

https://docs.djangoproject.com/en/dev/ref/templates/builtins/#escapejs

0👍

Since other approaches are not timezone aware, you can simply use the Django’s built-in Template Tag widthratio to convert python’s seconds to javascript’s milliseconds.

new Date({% widthratio selected_date|date:"U" 1 1000 %}

Leave a comment