将阿拉伯语日期格式转换为英语:System.FormatException:'String was not recognized as a valid DateTime.'

converting arabic date format to english : System.FormatException: 'String was not recognized as a valid DateTime.'

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

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

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

抛出异常:

System.FormatException: 'String was not recognized as a valid DateTime.'

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

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/

添加这个命名空间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);

Follow this link for fiddle. Code With Example

您可以尝试将 数字 东方阿拉伯语)转换为 西方阿拉伯语 (即进入 0..9):

  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