且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何为非英语语言(如阿拉伯语)使用DateTime.TryParse()

更新时间:2023-11-29 13:37:40

如果您知道确切的格式,您可以强制使用 TryParseExact

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

结果是الأربعاء16مارس2011,这可以看得比我好)与您的输入在一个字符不同:.NET使用(并期望)hamza,您的输入没有它。如果我们以这种方式修改输入,一切正常:

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