【问题标题】:how to get DateTime format to provide Date Month and Year based on Culture of the website?如何根据网站的文化获取 DateTime 格式以提供日期月份和年份?
【发布时间】:2020-05-15 13:24:45
【问题描述】:

我正在尝试根据特定格式的网站内容文化获取日期。

我希望日期格式为 Date Month Year

de-DE 文化 1. 2008 年十月 zh-CN 文化 2008 年 10 月 1 日 es-ES 文化 01 de octubre de 2008 FR-FR 文化 2008 年 10 月 1 日

我试过了 datetimeObject.ToString("m", contentCultureObject) 导致

de-DE 文化 01 十月 zh-CN 文化 10 月 1 日 es-ES 文化 01 octubre fr-FR 文化 10 月 1 日

我也试过datetimeObject.ToString("Y", contentCultureObject),结果是

de-DE 文化 2008 年十月 zh-CN 文化 2008 年 10 月 es-ES 文化 2008 年 8 月 fr-FR 文化 2008 年 10 月

基本上我想结合“m”和“Y”格式来实现所需的输出。 请帮忙。

【问题讨论】:

  • 请说明您想要什么,因为您说“我想要它在日期月份年份”,但随后显示的示例顺序不同,例如“2008 年 10 月 1 日”,即月份日期年份。那么,这是您得到但不想要的,还是您真正想要的示例?
  • 如果您需要的格式在 .NET 中不受支持,您别无选择,只能硬编码每种支持的文化所需的格式。

标签: c# .net datetime sitecore


【解决方案1】:
//you can write your desired Culture 

CultureInfo ci = CultureInfo.CreateSpecificCulture("es-ES");
    ci.DateTimeFormat.ShortDatePattern = "d MMMM yyyy";
    ci.DateTimeFormat.FullDateTimePattern = "d MMMM yyyy h:m:ss";
    Thread.CurrentThread.CurrentCulture = ci;

//then call
datetimeObject.ToString();

【讨论】:

  • 感谢您的回复。这对我来说是不可能的,因为目前我们的解决方案中有大约 28 种文化,而且总是有可能添加更多。我想要的是一种适用于所有文化的通用方法。如果添加新语言,这种通用方法还将使我们免于代码更改和部署。
  • 也许这对你有用 CultureInfo ci = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);
  • 这将使所有文化都具有相同的日期格式,对吧?
  • 不幸的是,我认为.NET 不支持您需要的格式。您可能别无选择,只能为所有文化选择一种通用格式,或编码每种文化格式。
  • @WowoOt:感谢您的回复。我能够从您的回复中找出解决方案。
【解决方案2】:

我可以通过替换 FullDateTimePattern 字符串来做到这一点。

这就是我所做的:

string currentCulturePattern = contentCultureObject.DateTimeFormat.LongDatePattern;
string requiredPattern = currentCulturePattern.Replace("dddd,", String.Empty).Replace("dddd", String.Empty).Trim();
dateTimeObject.ToString(requiredPattern, contentCultureObject);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-05-19
    • 2021-12-16
    • 1970-01-01
    • 2012-02-16
    • 1970-01-01
    • 1970-01-01
    • 2020-07-31
    • 2011-05-23
    相关资源
    最近更新 更多