简体   繁体   English

为什么本地PC和服务器上的日期格式不同

[英]Why is date format different on local PC and server

We are developing .NET Core 2.2 application.我们正在开发.NET Core 2.2应用程序。 We noticed that date format is different on localhost than on the remote server.我们注意到本地主机上的日期格式与远程服务器上的不同。

  • Localhost: 18. 06. 2020 15:12:53本地主机: 18. 06. 2020 15:12:53
  • Remote IIS server: 18.6.2020 15:12:53远程 IIS 服务器: 18.6.2020 15:12:53

Date is displayed in *.cshtml using @Html.DisplayFor(model => model.CreatedAt) .使用@Html.DisplayFor(model => model.CreatedAt)*.cshtml中显示日期。 Why is date format different although localhost and server use the same Startup.cs file?尽管 localhost 和服务器使用相同的Startup.cs文件,为什么日期格式不同? We want to have the format that the remote server produces on localhost as well.我们也希望拥有远程服务器在 localhost 上生成的格式。

Startup.cs :启动.cs

public void ConfigureServices(IServiceCollection services)
{
    ...    
    services.Configure<RequestLocalizationOptions>(options =>
    {
        options.DefaultRequestCulture = new Microsoft.AspNetCore.Localization.RequestCulture("sl-SI");
        options.SupportedCultures = new List<CultureInfo> { new CultureInfo("sl-SI") };
    });
    ...
}

public void Configure(IApplicationBuilder app)
{
    ...
    app.UseRequestLocalization();
    ...
}

I encountered similar issue and below code solved my issue.我遇到了类似的问题,下面的代码解决了我的问题。

Apply Culture inside Configure like below.Configure中应用Culture ,如下所示。

public void Configure(IApplicationBuilder app)
{
    var cultureInfo = new System.Globalization.CultureInfo("sl-SI");
    System.Globalization.CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
    System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;

    // your code
}

Edit I would recommend using culture value from the appsettings.json .编辑我建议使用appsettings.json中的culture值。 This way in future you need to update culture you don't need new build.这样,将来您需要更新不需要新构建的文化。 Just update appsettings.json and restart the server will work.只需更新appsettings.json并重新启动服务器即可。

public void Configure(IApplicationBuilder app)
{
    // Get Culture Info from appsettings and set Default culture for application.
    // If not found culture value from appsettings then use "sl-SI"
    var culture = Configuration.GetValue<string>("AppSettings:Culture") ?? "sl-SI";
    var cultureInfo = new System.Globalization.CultureInfo(culture);
    System.Globalization.CultureInfo.DefaultThreadCurrentCulture = cultureInfo;
    System.Globalization.CultureInfo.DefaultThreadCurrentUICulture = cultureInfo;

    // your code
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM