在组件中的 Blazor WebAssembly 中,假设文化是正确的,如何使 DateTime.ToString 使用当前文化的日期格式?

In Blazor WebAssembly in a component, how can I make DateTime.ToString use the date format of the current culture, assuming the culture is correct?

我暂时将我的浏览器语言和区域设置为英语 - 英国,即使我在美国也是如此。我已删除“en-US”,现在将“en-GB”作为我唯一的语言偏好。

在我的 Blazor WebAssembly 站点中,在一个组件上,我有一个 属性 returns 一个字符串:myDate.ToString("d") + System.Globalization.CultureInfo.CurrentCulture.DisplayName; 在我的页面上呈现为 6/27/2020en (GB),其中myDate 是一个 DateTime,设置为 2020 年 6 月 27 日 00:00:00.000。我的 Blazor 站点设置了 app.UseRequestLocalization(...) 中间件。

不应该以英国格式显示日期,即 27/06/2020?我只能猜测 CultureInfo.CurrentCulture 没有正确设置 ShortDatePattern。可能是什么?

更新:所有 WebAssembly 组件输出显示 DateTimeFormatInfo.CurrentInfo.ShortDatePattern == "M/d/yyyy" 即使 CultureInfo.CurrentCulture.Name == "en-GB"。为什么会这样?是什么从文化中设置了 ShortDatePattern,我可以“重新初始化”它吗?

myDate.ToString("d", System.Globalization.CultureInfo.GetCultureInfo("en-GB"));的显式调用仍然奇怪地输出M/d/yyyy格式(U.S.格式)。 为什么会这样?

更新 2:我创建了一个最小示例:File-New Project、Blazor Web Assembly、.NET 5 ASP.NET Core 托管。我将 App.Razor 替换为以下内容:

<div> current culture @(System.Globalization.CultureInfo.CurrentCulture.Name) </div>
<div> current date format @(System.Globalization.CultureInfo.CurrentCulture.DateTimeFormat.ShortDatePattern) </div>
<div> today @DateTime.Now.ToString("d") </div>

结果(出乎意料):

Firefox 浏览器设置(Edge 和 Chrome 相似并显示相同的问题):

这导致发送 Accept-Language: en-GB,en-US;q=0.7,en;q=0.3——这似乎是“更喜欢 en-GB”的正确方法,并导致 CultureInfo.CurrentCulture 具有正确的值。

我已经用 Microsoft.AspNetCore.Components.WebAssembly 试过了。* nuget 包版本 5.0.9、5.0.11 - 两者都显示相同的错误结果。

更新 3:相同的最小项目在 6.0.0-rc.1 中工作并提供正确的日期格式! 这真的是他们从未修复过的 Blazor 5 错误吗?

对于 .NET 6+,这似乎已修复。

对于 .NET 5,我找不到根本原因,因此我需要编写此解决方法的代码,需要时需要显式调用它。显然,如果我们能找到更好的解决方案来允许按预期使用 DateTime.ToString,这是不可取的。

/// <summary>
/// Returns a short date-only string from a date/time value, based on the user's current culture.
/// </summary>
public static string ToLocalShortDate(this DateTime value)
{
    // this is needed because I can't get localization to work -- see 
    //   (if we can fix, better to use DateTime.ToString("d"))

    string format;
    // countries taken from https://en.wikipedia.org/wiki/Date_format_by_country
    if (CurrentCulture.Name.EndsWithAny("US", "CA", "ZA", "KE", "GH", "en"))
        format = "MM/dd/yyyy";
    else if (CurrentCulture.Name.EndsWithAny("CN", "JP", "KR", "KP", "TW", "HU", "MN", "LT", "BT"))
        format = "yyyy-MM-dd";
    else format = "dd/MM/yyyy";

    return value.ToString(format);
}
        
/// <summary>
/// Returns true if and only if a string ends with any of some strings.
/// The value will not match a null reference.
/// </summary>
public static bool EndsWithAny(this string value, params string[] allowedValues) =>
    allowedValues != null && value != null && allowedValues.Any(s => CurrentCulture.Name.EndsWith(s));