英文:
Django: Format dates according to settings.LANGUAGE_CODE in code (e.g. messages)
问题
在我的Django 4.2应用的settings.py
文件中,我有以下配置:
# 国际化
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = "de-CH"
TIME_ZONE = "CET"
USE_I18N = True
USE_TZ = True
这在模板中有效,例如,{{ training.date | date:"l, j. M." }}
显示为Sonntag, 11. Jun.
。
但是,如果我在代码中使用strftime
,例如:
self.success_message = (
f"Eingeschrieben für <b>{self.date.strftime('%A')}</b>, "
f"den {self.date.strftime('%d. %B %Y')}."
)
我会得到Eingeschrieben für Thursday, den 15. June 2023.
。
如何在代码中根据settings.LANGUAGE_CODE
获取日期字符串?
英文:
In my Django 4.2 app's settings.py
I have
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = "de-CH"
TIME_ZONE = "CET"
USE_I18N = True
USE_TZ = True
which works in templates, e.g. {{ training.date | date:"l, j. M." }}
is displayed as Sonntag, 11. Jun.
.
However, if I use strftime
in the code, e.g.
self.success_message = (
f"Eingeschrieben für <b>{self.date.strftime('%A')}</b>, "
f"den {self.date.strftime('%d. %B %Y')}.".replace(" 0", " ")
)
I end up with Eingeschrieben für Thursday, den 15. June 2023.
.
How do I get get date strings according to settings.LANGUAGE_CODE
from code?
答案1
得分: 1
format_date
在这里非常有用,它会根据当前的语言环境获取日期的字符串表示。
首先,我们导入它:from django.utils import formats
,然后将你的代码修改成这样:
self.success_message = (
f"已注册于 <b>{formats.date_format(self.date, 'l')}</b>, "
f"{formats.date_format(self.date, 'j. F Y')}."
).replace(" 0", " ")
英文:
format_date
would be great here, it get a string representation of a date according to the current locale
first we import it from django.utils import formats
then change your code like that
self.success_message = (
f"Eingeschrieben für <b>{formats.date_format(self.date, 'l')}</b>, "
f"den {formats.date_format(self.date, 'j. F Y')}.".replace(" 0", " ")
)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论