将阿拉伯日期格式转换为英语:System.FormatException:'字符串未被识别为有效的DateTime。'

时间:2019-10-02 07:46:55

标签: c# datetime cultureinfo culture

在我的C#代码中,我从一个函数中获得一个阿拉伯语日期,我需要将此日期转换为英语格式(UK/US)。我尝试了以下代码

string startdate = "٢٠١٩-٠٩-٠٣";

var dateTime = DateTime.ParseExact(
  startdate, 
 "d MMMM yyyy", 
  CultureInfo.InvariantCulture);

引发异常:

  

System.FormatException:'字符串未被识别为有效字符串   日期时间。”

3 个答案:

答案 0 :(得分:1)

您可以尝试将个数字(它们是东阿拉伯语)转换为西阿拉伯语(即转换为0..9):< / p>

  string startdate = @"٢٠١٩-٠٩-٠٣";

  string translated = string.Concat(startdate.Select(c => char.GetNumericValue(c) < 0 
     ? c.ToString()                          // Character, keep intact  
     : char.GetNumericValue(c).ToString())); // Digit! we want them be 0..9 only

  // Arabic language has right to left order, that's why pattern is "yyyy-M-d"
  DateTime dateTime = DateTime.ParseExact(
    translated, // note, not startdate
   "yyyy-M-d", 
    CultureInfo.InvariantCulture, 
    DateTimeStyles.AssumeLocal);

  // English, Great Britain culture
  Console.Write(dateTime.ToString("d MMMM yyyy", CultureInfo.GetCultureInfo("en-GB")));

结果:

  3 September 2019

Fiddle

答案 1 :(得分:0)

尝试指定您要解析的字符串的区域性:

var culture = CultureInfo.GetCultureInfo("YOUR CULTURE CODE"); // Probably "ar-SA"
var startDate = "٢٠١٩-٠٩-٠٣";
var dateTime = DateTime.ParseExact(startDate, "d MMMM yyyy", culture);

您可以在这里找到文化代码:

http://www.csharp-examples.net/culture-names/

答案 2 :(得分:0)

添加此命名空间using System.Globalization;

string arabicTextDate= "٢٠١٩-٠٩-٠٣";
     var str = arabicTextDate
    .Replace('\u0660','0')
    .Replace('\u0661','1')
    .Replace('\u0662','2')
    .Replace('\u0663','3')
    .Replace('\u0664','4')
    .Replace('\u0665','5')
    .Replace('\u0666','6')
    .Replace('\u0667','7')
    .Replace('\u0668','8')
    .Replace('\u0669','9');
    DateTime dt=DateTime.ParseExact(str, "yyyy-MM-dd", CultureInfo.InvariantCulture);
  

点击此链接以进行提琴。 Code With Example

enter image description here