1 year ago

#18628

test-img

UtechIr

Use different calender and format info for DateTime.ToString() and DateTime.Parse() in Asp.Net Core 5

I use globalization and localization in my Asp.Net Core app and i want to use PersianCalendar when requested culture is set to 'fa-IR'.

This needs to happen whenever a DateTime.ToString() happens. I want it to be converted to persian date automatically and i don't want to change the code that is calling ToString() method (because other cultures still needs to see gregorian calendar).

The request localization works fine and CultureInfo.CurrentCulture is correclty set to 'fa-IR' but the default calendar for 'fa-IR' culture is GregorianCalendar.

So i created a subclass of CultureInfo like this:

public class PersianCulture : CultureInfo
{
    private readonly Calendar _calendar;
    private readonly Calendar[] _optionalCalendars;
    private DateTimeFormatInfo _dateTimeFormatInfo;

    public PersianCulture() : base("fa-IR") {
        _calendar = new PersianCalendar();

        _optionalCalendars = new List<Calendar>
        {
            new PersianCalendar(),
            new GregorianCalendar()
        }.ToArray();

        var dateTimeFormatInfo = CultureInfo.CreateSpecificCulture("fa-IR").DateTimeFormat;
        dateTimeFormatInfo.Calendar = _calendar;
        _dateTimeFormatInfo = dateTimeFormatInfo;
    }

    public override Calendar Calendar => _calendar;

    public override Calendar[] OptionalCalendars => _optionalCalendars;

    public override DateTimeFormatInfo DateTimeFormat {
        get => _dateTimeFormatInfo;
        set => _dateTimeFormatInfo = value;
    }
}

Then i added a middleware that checks if requested culture is 'fa-IR' then sets the CurrentCulture to PersianCulture as follows:

if ( CultureInfo.CurrentCulture.Name == "fa-IR" ) {
        var culture = new PersianCulture();
        CultureInfo.CurrentCulture = culture;
        CultureInfo.CurrentUICulture = culture;
   }

And i get the expected result. Whenever a someDate.ToString() is called the output is converted to persian date. For exapmle DateTime.Now.ToString() will output 16/10/1400 02:53:40 ب.ظ.

The problem is the same Calendar and DateTimeFormatInfo is used whenever a DateTime.Parse() happens and the parsed date will be wrong because the source is in gregorian format but treated as persian.

How can i use my custom PersianCulture class for converting to string and use C# default's 'fa-IR' calendar for parsing dates?

c#

asp.net-core

datetime

globalization

persian-calendar

0 Answers

Your Answer

Accepted video resources