[Django]-Get datetime mask for a given locale

5👍

Use the django.utils.formats module:

from django.utils import formats
date_format = get_format('DATE_FORMAT')

get_format(format_type, lang=None, use_l10n=None) returns the current format used; set use_l10n to force localisation to be applied (defaults to your settings.USE_L10N flag), or use the lang argument to pick a specific language:

>>> from django.utils import formats
>>> formats.get_format('DATE_FORMAT')
'N j, Y'
>>> formats.get_format('DATE_FORMAT', lang='de')
'j. F Y'

See the available date format strings to see what the various strings mean.

Alternatively, use the javascript catalog view, which includes JavaScript get_format() function.

Either way, the Django format is not a JS-recognized format. You have two options:

  • Use this Django snippet to add a . strfdate() method to the JavaScript Date prototype that recognises Django formats, or

  • Install the django-missing library which includes an updated version of the above snippet as a ready-to-include JS library.

If you need a JS-compatible mask, you’ll need to do the translation yourself, based on those two .strfdate() examples.

Leave a comment