Opened 12 years ago

Closed 12 years ago

Last modified 12 years ago

#20006 closed Bug (worksforme)

Converting a datestring into a proper date from and AJAX call

Reported by: erik@… Owned by: nobody
Component: Internationalization Version: 1.5
Severity: Normal Keywords: get_format L10N
Cc: Triage Stage: Unreviewed
Has patch: no Needs documentation: no
Needs tests: no Patch needs improvement: no
Easy pickings: no UI/UX: no

Description

When an AJAX call passes a date in a Django L10N/I18N site, the date will be a string, formatted according to the current users locale.

This means that on the server, Django needs to convert this string into a proper date, taking the locale of the user into account. I can't find a way to do so.
The only lead I have found was to use Python's time.strptime() function, and use Django's django.utils.formats.get_format() function to pass it the correct format. However, Django's get_format() function returns "j-n-Y" for me (user with Dutch locale), which is not a valid format for the strptime() function.

USE_L10N is True, and USE_I18N is also True.

def StringToDate(datestring):
    from django.utils.formats import get_format
    from time import strptime
    short_datetime_format = get_format("SHORT_DATE_FORMAT")
    return strptime(datestring, short_datetime_format)


ValueError: time data u'08-03-2013' does not match format 'j-n-Y'

Change History (2)

comment:1 by Claude Paroz, 12 years ago

Resolution: worksforme
Status: newclosed

If you are passing your value through the forms API (and a DateField), you should be safe. Otherwise, see django.forms.fields.BaseTemporalField.to_python method if you want to emulate a similar behaviour in custom code.

If you still think there is a bug somewhere, please try to provide a test case to reproduce it.

comment:2 by erik@…, 12 years ago

Thank you claudep,

For anyone Googling, the solution would be something like this:

        from django.forms.fields import DateField

        dt = request.GET.get('date', '')
        fld = DateField()
        formatted_datetime = fld.to_python(dt)
Note: See TracTickets for help on using tickets.
Back to Top