Search code examples
c#datetimecultureinfoculture

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


In my c# code, I am getting an Arabic date from a function, I need to convert this date to English format (UK/US). I tried with the following code

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

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

it throws exception:

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


Solution

  • Add this namespace 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

    enter image description here