问题
What would be the easy way of achieving such below? selected_date comes from django context as a python date :
<script type="text/javascript">
var selected_year = {{ selected_date|date:"Y" }}
var selected_month = {{ selected_date|date:"m" }} - 1;
var selected_day = {{ selected_date|date:"d"}}
var selected_date = new Date(selected_year, selected_month, selected_day);
alert(selected_date);
</script>
回答1:
I've had a lot of success with the isoformat function in python:
var selected_date = new Date("{{ selected_date.isoformat }}")
回答2:
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'
回答3:
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
回答4:
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
回答5:
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 %}
来源:https://stackoverflow.com/questions/5076319/django-date-to-javascript-at-the-template