是否可以根据语言环境更改时间格式?
让我们来看看以下情况
所以我的最终问题是,如何基于asp.net核心c#中的语言环境设置时间?
我已经完成了带日期的本地化,但是我也需要时间。
上图显示了AM / PM。同样,我需要显示24小时格式的时隙,具体取决于语言环境。
答案 0 :(得分:2)
好的,我希望这就是你想要的。
首先,您需要支持实际的区域性并在应用程序启动时对其进行配置。
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
对象从应用程序推送到客户端时,它将在当前客户端区域设置中对其进行解析。
如果您使用的是Google Chrome浏览器,并且要对此进行测试,则只需转到chrome://settings/languages
即可更改浏览器的语言环境并更改设置。重新启动Chrome,您应该会立即看到更改。
答案 1 :(得分:0)
如果您已很好地完成了本地化,则无需执行其他步骤即可以本地格式显示时间,
但以防万一;您可以通过提供以下自己的格式(在@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()