是否可以根据区域设置更改时间格式?
我们来看下面的场景
所以我的最终问题是,如何根据asp.net core c#中的语言环境设置时间?
我已经完成了日期本地化,但我也必须按时完成。
上图显示AM / PM。同样,我需要以24小时格式显示时间段,这是根据区域设置决定的。
好的,我希望这就是你想要的。
首先,您需要支持实际的文化并在应用程序启动时配置它们。
public void ConfigureServices(IServiceCollection services)
{
/*boilerplate code omitted*/
// Configure supported cultures and localization options
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("de-DE"),
new CultureInfo("fr"),
new CultureInfo("ar-YE")
};
// State what the default culture for your application is. This will be used if no specific culture
// can be determined for a given request.
options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
// You must explicitly state which cultures your application supports.
// These are the cultures the app supports for formatting numbers, dates, etc.
options.SupportedCultures = supportedCultures;
// These are the cultures the app supports for UI strings, i.e. we have localized resources for.
options.SupportedUICultures = supportedCultures;
});
}
然后,您需要实际使用请求本地化
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
var locOptions = app.ApplicationServices.GetService<IOptions<RequestLocalizationOptions>>();
app.UseRequestLocalization(locOptions.Value);
app.UseStaticFiles();
app.UseMvc(routes =>
{
routes.MapRoute(
name: "default",
template: "{controller=Home}/{action=Index}/{id?}");
});
}
现在,每当您将Date
对象从应用程序推送到客户端时,它将在当前客户端区域设置中解析它。
如果您使用的是谷歌浏览器并希望对其进行测试,您只需访问chrome://settings/languages
即可更改浏览器区域设置并更改设置。重新启动Chrome,您应该立即看到更改。
如果您已完成本地化,则无需执行其他步骤以本地格式显示时间,
但为了以防万一;您可以通过提供以下格式(从@Marco的回复中修改的代码)来配置本地化,同时定义特定文化的时间格式:
public void ConfigureServices(IServiceCollection services)
{
/*boilerplate code omitted*/
// Configure supported cultures and localization options
services.Configure<RequestLocalizationOptions>(options =>
{
var supportedCultures = new[]
{
new CultureInfo("en-US"),
new CultureInfo("de-DE"),
new CultureInfo("fr"),
new CultureInfo("ar-YE") {
DateTimeFormat = {
// change long time pattern to 24 hours
// e.g. 13:50:21
LongTimePattern = "HH:mm:ss",
// short time pattern as 12 hours
// e.g. 01:50:21 PM
ShortTimePattern = "hh:mm tt"
},
}
};
// State what the default culture for your application is. This will be used if no specific culture
// can be determined for a given request.
options.DefaultRequestCulture = new RequestCulture(culture: "en-US", uiCulture: "en-US");
// You must explicitly state which cultures your application supports.
// These are the cultures the app supports for formatting numbers, dates, etc.
options.SupportedCultures = supportedCultures;
// These are the cultures the app supports for UI strings, i.e. we have localized resources for.
options.SupportedUICultures = supportedCultures;
});
}
在您的视图中,您必须调用相关模式:
DateTime.Now.ToLongTimeString()
要么
DateTime.Now.ToShortTimeString()