How do I use DateTime.TryParse() for non-English languages like Arabic?

你。 提交于 2019-11-28 11:19:36

If you know the exact format, you can force its use with TryParseExact:

b = DateTime.TryParseExact(sample, "dddd d MMMM yyyy", provider, DateTimeStyles.None, out result);

However, in your case, this does not work. To find the problem, let’s try the other way round:

Console.WriteLine(expected.ToString("dddd d MMMM yyyy", provider));

And the result is “الأربعاء 16 مارس 2011”, which (you can probably read that better than me) differs from your input in one character: .NET uses (and expects) hamza, your input does not have it. If we modify the input in this way, everything works:

CultureInfo provider = new CultureInfo("ar-AE");    // Arabic - United Arab Emirates

string sample = "الأربعاء 16 مارس 2011"; // Arabic date in Gregorian calendar
DateTime result;
DateTime expected = new DateTime(2011, 3, 16);   // the expected date
bool b;

b = DateTime.TryParse(sample, provider, DateTimeStyles.None, out result);

Assert.IsTrue(b);
Assert.AreEqual(expected, result);
DateTime result = DateTime.Parse("الاربعاء 16 مارس 2011", new CultureInfo("ar-JO"));

But you can check the documentation : CultureInfo Class

maybe something like this:

int Year, DayOfMonth;
string Month;
string[] Months = new string[] {"ينایر","فبرایر","مارس","ابریل","مایو",...};//these texts are writen with persian keyboard,change the ی  with ي ,its really hard with my keymap
string[] Splits = Input.Split(" ");
foreach(string Split in Splits)
{
    if(Months.Contains(Split))
    {
        Month = Months.IndexOf(Split);
    }
    else
    {
        int Number;
        if(int.TryParse(Split, out Number))
        {
            if(Number<32)
            {
                DayOfMonth=Number;
            }
            else
            {
                Year=Number;
            }
        }
    }
}

if your going to support multiple calendars:
you should add all the calendars months in order in that array.
after december there should be the next calendar months ( rabi-ol-avval, rabi-ol-thani, ...)
then

int CalendarId = Month / 12;
Month %= 12;

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!