Time format based on locale in asp.net core

Viewed 4421

Is it possible to change the time format based on the locale?

Let's take below scenarios

  • Norway - 24hr time format is vastly used
  • Sweden - 24hr time format is vastly used
  • Switzerland German region - 12hr format is vastly used
  • Germany - 24hr format is vastly used

So my ultimate problem is, how to set time based on the locale in asp.net core c#?

I have done the localization with date but I have to do it for time as well.

enter image description here

above image shows with AM/PM. Likewise, I need to show time slots in 24 hr format which is decided based on the locale.

2 Answers

Ok, I hope this is what you want.

First of all, you need to support the actual cultures and configure them on the application startup.

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;
    });
}

Then you need to actually use the request localization

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?}");
    });
}

Now, whenever you push a Date object from your application to a client it will parse it in the current clients locale.

If you are using Google Chrome and want to test this you can simply go to chrome://settings/languages to change your browsers locale and change the settings. Restart Chrome and you should see the changes immediately.

Reference: https://github.com/aspnet/Entropy/blob/2fcbabef58c2c21845848c35e9d5e5f89b19adc5/samples/Localization.StarterWeb/Startup.cs

if you have done the localization well, you don't need to do additional steps to show time in local format,

but just in case; you can define time format for specific culture while configuring localization by providing your own format as below (the code modified from @Marco's reply):

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;
});
}

in your view you have to call related pattern :

DateTime.Now.ToLongTimeString()

or

DateTime.Now.ToShortTimeString()
Related