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'
- [Django]-MySQL vs PostgreSQL? Which should I choose for my Django project?
- [Django]-Django manage.py: Migration applied before its dependency
- [Django]-Startapp with manage.py to create app in another directory
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
- [Django]-Get the name of a decorated function?
- [Django]-Django 3.x – which ASGI server (Uvicorn vs. Daphne)
- [Django]-How to change status of JsonResponse in Django
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
- [Django]-How can I get a decimal field to show more decimal places in a template?
- [Django]-Complete django DB reset
- [Django]-How to set ForeignKey in CreateView?
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 %}
- [Django]-How to test "render to template" functions in django? (TDD)
- [Django]-Why is assertDictEqual needed if dicts can be compared by `==`?
- [Django]-Initial populating on Django Forms