Django:在代码中根据settings.LANGUAGE_CODE格式化日期(例如消息)。

huangapple go评论65阅读模式
英文:

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 = &quot;de-CH&quot;

TIME_ZONE = &quot;CET&quot;

USE_I18N = True

USE_TZ = True

which works in templates, e.g. {{ training.date | date:&quot;l, j. M.&quot; }} is displayed as Sonntag, 11. Jun..

However, if I use strftime in the code, e.g.

self.success_message = (
    f&quot;Eingeschrieben f&#252;r &lt;b&gt;{self.date.strftime(&#39;%A&#39;)}&lt;/b&gt;, &quot;
    f&quot;den {self.date.strftime(&#39;%d. %B %Y&#39;)}.&quot;.replace(&quot; 0&quot;, &quot; &quot;)
)

I end up with Eingeschrieben f&#252;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&quot;Eingeschrieben f&#252;r &lt;b&gt;{formats.date_format(self.date, &#39;l&#39;)}&lt;/b&gt;, &quot;
    f&quot;den {formats.date_format(self.date, &#39;j. F Y&#39;)}.&quot;.replace(&quot; 0&quot;, &quot; &quot;)
)

huangapple
  • 本文由 发表于 2023年6月11日 21:20:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76450658.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定