Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I need to convert strings to DateTime objects that are in non-English languages. I've seen many examples of converting DateTime to strings in other languages, but not the other way around.

This doesn't seem to work:

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

Additionally, I need to handle strings that are in other calendars. This is what I tried and it doesn't seem to work either.

CultureInfo provider = new CultureInfo("ar-AE");    // Arabic - United Arab Emirates
provider.DateTimeFormat.Calendar = new System.Globalization.HijriCalendar();
// Wednesday, March 16, 2011, 11 Rabi second in 1432
string sample = " ‏11 ربيع ثاني 1432 ";
DateTime result;
DateTime expected = new DateTime(2011, 3, 16);   // ?
bool b;

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

Assert.IsTrue(b);
Assert.AreEqual(expected, result);

What am I missing?

like image 502
Dan Bailiff Avatar asked Mar 16 '11 19:03

Dan Bailiff


1 Answers

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);
like image 78
Mormegil Avatar answered Sep 30 '22 01:09

Mormegil