Code

Opened 16 months ago

Closed 16 months ago

Last modified 16 months 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'

Attachments (0)

Change History (2)

comment:1 Changed 16 months ago by claudep

  • Needs documentation unset
  • Needs tests unset
  • Patch needs improvement unset
  • Resolution set to worksforme
  • Status changed from new to closed

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 Changed 16 months ago by erik@…

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)

Add Comment

Modify Ticket

Change Properties
<Author field>
Action
as closed
as The resolution will be set. Next status will be 'closed'
The resolution will be deleted. Next status will be 'new'
Author


E-mail address and user name can be saved in the Preferences.

 
Note: See TracTickets for help on using tickets.