How to enforce Gregorian calendar in all cultures in asp.net Core

Viewed 1434

We have an asp.net Core website which requires having different cultures available but we are having a problem when saving dates to the database due to different calendars.

How can we enforce the Gregorian calendar even if culture was changed?

    private readonly CultureInfo[] _supportedCultures = {
        new CultureInfo("ar"),
        new CultureInfo("en")
    };

what we want to is to make "ar" or any other culture use "en" dateformat...

Thank You

1 Answers

Well, you can always use CultureInfo.InvariantCulture/CultureInfo.InvariantUiCulture, or whatever your preferred culture is.

IStringLocalizer<T> has a .WithCulture(...) method, so you can create a localizer with that specific culture.

Something like this (untested):

IStringLocalizer<SharedResource> localizer = ..;
var invariantLocalizer = localizer.WithCulture(CultureInfo.InvariantCulture);

// where "ShowDate" is "Today is {0}" in the resx
var neutralLocalizer = invariantLocalizer["ShowDate", DateTime.Now];

In MVC Views you can define it globally for each view in Views/_ViewImports.cshtml/Views/_ViewStart.cshtml:

@inject Microsoft.ApplicationInsights.Extensibility.TelemetryConfiguration TelemetryConfiguration
@inject IHtmlLocalizer<Startup> Localizer
@{ 
    var InvariantLocalizer = Localizer.WithCulture(CultureInfo.InvariantCulture);
}

Optionally you can also set the calendar of a given culture.

var current = System.Globalization.CultureInfo.CurrentCulture;
current.DateTimeFormat.Calendar = new GregorianCalendar();

as shown in the Dates and calendars.

Related