Andreas Fritz
Andreas Fritz

Reputation: 65

Parse arabic date in c#

In an application that I'm writing I want to parse a specific date which is in the arabic language in c#. For example the date could look like this: ٣٠.١٢.١٩٨٩

But I want this output: 30.12.1989

My question is how to do that in c# to get a DateTime object out of this string.

Can anyone tell me how to to this?

Upvotes: 1

Views: 1489

Answers (1)

Soner Gönül
Soner Gönül

Reputation: 98840

Eastern Arabic numerals does not supported by DateTime parsing methods, they only accepts Arabic numerals.

On the other hand, char.GetNumericValue method is quite good to get a floating-point representation of a numeric Unicode character as a double which perfectly successful for Eastern Arabic numerals as well.

If your string is always dd.MM.yyyy format based on those numerals, you can split your string with . and get their numeric values from those character, parse to integer those parts, use them in a DateTime(year, month, day) constructor and get it's string representation with dd.MM.yyyy format with a culture that using Gregorian Calendar as a Calendar property like InvariantCulture.

var s = "٣٠.١٢.١٩٨٩";
var day =   Int32.Parse(string.Join("",
                        s.Split('.')[0].Select(c => char.GetNumericValue(c)))); // 30
var month = Int32.Parse(string.Join("",
                        s.Split('.')[1].Select(c => char.GetNumericValue(c)))); // 12
var year =  Int32.Parse(string.Join("",
                        s.Split('.')[2].Select(c => char.GetNumericValue(c)))); // 1989

var dt = new DateTime(year, month, day);
Console.WriteLine(dt.ToString("dd.MM.yyyy", CultureInfo.InvariantCulture)); // 30.12.1989

Here a demonstration.

As an alternative, you can create your own Dictionary<char, char> structure and you can replace Eastern Arabic characters mapped with Western Arabic characters.

var mapEasternToWestern = new Dictionary<char, char>
{ 
    {'٠', '0'}, 
    {'١', '1'}, 
    {'٢', '2'}, 
    {'٣', '3'}, 
    {'٤', '4'}, 
    {'٥', '5'}, 
    {'٦', '6'}, 
    {'٧', '7'}, 
    {'٨', '8'}, 
    {'٩', '9'}
};

Upvotes: 3

Related Questions