如何为非英语语言(如阿拉伯语)使用DateTime.TryParse() [英] How do I use DateTime.TryParse() for non-English languages like Arabic?

查看:165
本文介绍了如何为非英语语言(如阿拉伯语)使用DateTime.TryParse()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将字符串转换为非英语语言的DateTime对象。我看到很多例子,将DateTime转换为其他语言的字符串,但不是其他语言。

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.

这似乎不起作用:

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

我缺少什么?

推荐答案

如果您知道确切的格式,您可以强制使用 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);

这篇关于如何为非英语语言(如阿拉伯语)使用DateTime.TryParse()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆