我在解析日期时遇到了问题,程序被阿拉伯日期绊倒了。出于某种原因,DateTime.TryParse()
为这种文化输出垃圾。这是说明我的问题的示例代码:
var culture = CultureInfo.CreateSpecificCulture("ar");
DateTime date;
if (DateTime.TryParse(
"15/01/16",
culture,
DateTimeStyles.None,
out date))
{
Console.WriteLine("TryParse with Arabic culture: " + date);
}
if (DateTime.TryParseExact(
"15/01/16",
culture.DateTimeFormat.ShortDatePattern, // dd/MM/yy
culture,
DateTimeStyles.None,
out date))
{
Console.WriteLine("TryParseExact with Arabic short date pattern and culture: " + date);
}
if (DateTime.TryParseExact(
"15/01/16",
culture.DateTimeFormat.ShortDatePattern, // dd/MM/yy
CultureInfo.InvariantCulture,
DateTimeStyles.None,
out date))
{
Console.WriteLine("TryParseExact with Arabic short date pattern and invariant culture: " + date);
}
输出是这样的:
TryParse with Arabic culture: 1995-06-13 00:00:00
TryParseExact with Arabic short date pattern and culture: 1995-06-13 00:00:00
TryParseExact with Arabic short date pattern and invariant culture: 2016-01-15 00:00:00
只有最后一个版本有效,我不明白为什么前两个版本失败了。我可以理解 TryParse
失败是因为它无法弄清楚要使用哪种模式;但是在 TryParseExact
中我指定了确切的格式,它仍然无法正确解析。我不明白为什么会这样。
最佳答案
第三个其实不是阿拉伯语。它是一种文化不敏感的文化,可以始终在任何 .NET 应用程序中使用。这就是它在 TryParseExact
中返回当前日期时间值的原因。 Refer
阿拉伯文化不使用公历作为其默认日历。它使用农历 (UmAlQuraCalendar)。因此,您的日期被视为农历日期并转换回公历。
关于c# - 在 C# 中解析阿拉伯日期?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34742217/